//
//  GameScene.swift
//  FlappySquareMaybe
//
//  Created by pgAgent on 6/7/17.
//  Copyright © 2017 RJM Programming. All rights reserved.
//

import SpriteKit
#if os(watchOS)
    import WatchKit
    // SKColor typealias does not seem to be exposed on watchOS SpriteKit
    typealias SKColor = UIColor
#endif

class GameScene: SKScene, SKPhysicsContactDelegate  {
    
    
    fileprivate var label : SKLabelNode?
    fileprivate var spinnyNode : SKShapeNode?
    fileprivate var ylight : SKLightNode?
    fileprivate var ourcs : SKSpriteNode?
    fileprivate var ourobstacle : SKSpriteNode?
    fileprivate var ouran : SKAudioNode?
    public var anobstacle = SKSpriteNode()
    
    //init your categoryBitMask :
    public var carCategory:UInt32 = 0x1 << 0
    public var slowCarCategory:UInt32 = 0x1 << 1
    
    var totalDistance = CGFloat(0.0);
    var penUp = true;
    var lastX = CGFloat(0.0);
    var lastY = CGFloat(0.0);
    
    class func newGameScene() -> GameScene {
        // Load 'GameScene.sks' as an SKScene.
        guard let scene = SKScene(fileNamed: "GameScene") as? GameScene else {
            print("Failed to load GameScene.sks")
            abort()
        }
        
        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill
        
        return scene
    }
    
    func lightWithFinger(at pos: CGPoint){
        if let yourcs = self.ourcs?.copy() as! SKSpriteNode? {
            yourcs.position = pos
            yourcs.name = "notspinny"
            yourcs.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 1, height: 1))
            yourcs.physicsBody?.categoryBitMask = carCategory
            yourcs.physicsBody?.collisionBitMask = slowCarCategory
            yourcs.physicsBody?.contactTestBitMask = slowCarCategory
            yourcs.physicsBody?.isDynamic = false
            self.addChild(yourcs)
        }
        if let plight = self.ylight?.copy() as! SKLightNode? {
            plight.position = pos
            plight.lightColor = SKColor.orange
            plight.categoryBitMask = 0b0001
            plight.isEnabled = true
            self.addChild(plight)
        }
   }

    
    func setUpScene() {
        //self.physicsWorld.contactDelegate = self
        
        // Get sprite node for obstacle
        //self.ourobstacle = SKSpriteNode(fileNamed: "ourobstacle")
        //self.addChild(ourobstacle)
        
        
        // Get sprite node
        let pl = CGPoint(x: 0.0, y: 0.0)
        ourcs = SKSpriteNode(imageNamed: "rocket.png")
        ourcs?.name = "notspinny"
        ourcs?.position = pl //CGPoint(x: 100, y: 100)
        //init car
        //ourcs?.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 1, height: 1))
        ourcs?.physicsBody?.categoryBitMask = carCategory
        ourcs?.physicsBody?.collisionBitMask = slowCarCategory
        ourcs?.physicsBody?.contactTestBitMask = slowCarCategory
        ourcs?.physicsBody?.isDynamic = true
        //self.ourcs?.affectedByGravity = false
        
        let negativeShader = SKShader(source: "void main() { " +
            "    gl_FragColor = vec4(1.0 - SKDefaultShading().rgb, SKDefaultShading().a); " +
            "}")
        self.ourcs?.shader = negativeShader
        self.ourcs?.anchorPoint = CGPoint(x: 0.5, y: 1.0)

        
        //self.addChild(ourcs)
        
        // Get light node
        if let ylight = self.childNode(withName: "light") as? SKLightNode {
            //ylight.lightColor = SKColor.white
            ylight.position = pl //self.convertPoint(toView: self.view)
            ylight.lightColor = SKColor.orange
            ylight.categoryBitMask = 0b0001
            ylight.isEnabled = true
        } //        self.ylight = (self.childNode(withName: "ylight") as! SKLightNode)
        
        
        if 1 == 1 {
        if let ourcs = self.ourcs {
            ourcs.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
            ourcs.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                              SKAction.fadeOut(withDuration: 0.5),
                                              SKAction.removeFromParent()]))
            
            #if os(watchOS)
                // For watch we just periodically create one of these and let it spin
                // For other platforms we let user touch/mouse events create these
                ourcs.position = CGPoint(x: 0.0, y: 0.0)
                //spinnyNode.strokeColor = SKColor.red
                self.run(SKAction.repeatForever(SKAction.sequence([SKAction.wait(forDuration: 2.0),
                                                                   SKAction.run({
                                                                    let n = ourcs.copy() as! SKSpriteNode
                                                                    self.addChild(n)
                                                                   })])))
            #endif
        }
        }

        // Get label node from scene and store it for use later
       // self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
       // if let label = self.label {
       //     label.alpha = 0.0
       //     label.run(SKAction.fadeIn(withDuration: 2.0))
       // }
        
        // Create shape node to use during mouse interaction
        let w = (self.size.width + self.size.height) * 0.05
        self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)
        
        if let spinnyNode = self.spinnyNode {
            if let anobstacleNode = self.childNode(withName: "ourobstacle") as? SKSpriteNode {
                anobstacle = anobstacleNode
                if let atextureNode = self.childNode(withName: "rocket") as? SKTexture {
                    let rocketAnimation = SKAction.animate(with: [atextureNode],
                                                           timePerFrame: 0.1)
                    
                    anobstacle.run(rocketAnimation)
                }
                //init slowCar
                anobstacle.physicsBody = SKPhysicsBody(rectangleOf:   CGSize(width: 50, height: 50))
                anobstacle.physicsBody?.categoryBitMask = slowCarCategory
                anobstacle.physicsBody?.collisionBitMask = carCategory
                anobstacle.physicsBody?.contactTestBitMask = carCategory
                anobstacle.name = "obstacle"
                anobstacle.physicsBody?.isDynamic = false
                self.addChild(anobstacle)
                
            }
            spinnyNode.lineWidth = 4.0
            spinnyNode.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 1, height: 1))
            spinnyNode.physicsBody?.categoryBitMask = carCategory
            spinnyNode.physicsBody?.collisionBitMask = slowCarCategory
            spinnyNode.physicsBody?.contactTestBitMask = carCategory
            spinnyNode.name = "spinny"
            spinnyNode.physicsBody?.isDynamic = true
            spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
            spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                              SKAction.fadeOut(withDuration: 0.5),
                                              SKAction.removeFromParent()]))
            
            #if os(watchOS)
                // For watch we just periodically create one of these and let it spin
                // For other platforms we let user touch/mouse events create these
                spinnyNode.position = CGPoint(x: 0.0, y: 0.0)
                spinnyNode.strokeColor = SKColor.red
                //spinnyNode.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 10, height: 10))
                //spinnyNode.physicsBody?.categoryBitMask = slowCarCategory
                //spinnyNode.physicsBody?.collisionBitMask = carCategory
                //spinnyNode.physicsBody?.contactTestBitMask = carCategory
                //spinnyNode.name = "nonball"
                //spinnyNode.physicsBody?.isDynamic = false
                self.run(SKAction.repeatForever(SKAction.sequence([SKAction.wait(forDuration: 2.0),
                                                                   SKAction.run({
                                                                       let n = spinnyNode.copy() as! SKShapeNode
                                                                       self.addChild(n)
                                                                   })])))
            #endif
        }
        
        // Delegate
        //self.physicsWorld.contactDelegate = self
    }
    
    
    #if os(watchOS)
    override func sceneDidLoad() {
        self.setUpScene()
        if let anobstacleNode = self.childNode(withName: "ourobstacle") as? SKSpriteNode {
            anobstacle = anobstacleNode
            if let atextureNode = self.childNode(withName: "rocket") as? SKTexture {
                let rocketAnimation = SKAction.animate(with: [atextureNode],
                                                       timePerFrame: 0.1)
                
                anobstacle.run(rocketAnimation)
            }
            //init slowCar
            anobstacle.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 10, height: 10))
            anobstacle.physicsBody?.categoryBitMask = slowCarCategory
            anobstacle.physicsBody?.collisionBitMask = carCategory
            anobstacle.physicsBody?.contactTestBitMask = carCategory
            anobstacle.name = "obstacle"
            anobstacle.physicsBody?.isDynamic = false
            self.addChild(anobstacle)
            
        }
        physicsWorld.contactDelegate = self
    }
    #else
    override func didMove(to view: SKView) {
        self.setUpScene()
    if let anobstacleNode = self.childNode(withName: "ourobstacle") as? SKSpriteNode {
    anobstacle = anobstacleNode
    if let atextureNode = self.childNode(withName: "rocket") as? SKTexture {
    let rocketAnimation = SKAction.animate(with: [atextureNode],
    timePerFrame: 0.1)
    
    anobstacle.run(rocketAnimation)
    }
    //init slowCar
    anobstacle.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 10, height: 10))
    anobstacle.physicsBody?.categoryBitMask = slowCarCategory
    anobstacle.physicsBody?.collisionBitMask = carCategory
    anobstacle.physicsBody?.contactTestBitMask = carCategory
    anobstacle.name = "obstacle"
    anobstacle.physicsBody?.isDynamic = false
    self.addChild(anobstacle)
    
    }
        physicsWorld.contactDelegate = self
    }
    #endif

    func makeSpinny(at pos: CGPoint, color: SKColor) {
        if let spinny = self.spinnyNode?.copy() as! SKShapeNode? {
            spinny.position = pos
            spinny.strokeColor = color
            //spinny.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 10, height: 10))
            //spinny.physicsBody?.categoryBitMask = slowCarCategory
            //spinny.physicsBody?.collisionBitMask = carCategory
            //spinny.physicsBody?.contactTestBitMask = carCategory
            //spinny.name = "nonball"
            //spinny.physicsBody?.isDynamic = false
            self.addChild(spinny)
        }
    }
    
    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }
}


#if os(iOS) || os(tvOS)
// Touch-based event handling
extension GameScene {

    
    // set your contact function
    func didBegin(_ contact: SKPhysicsContact)
    {
        if contact.bodyA.node?.name == "obstacle" {
            totalDistance = pow(totalDistance,0.5)
            if totalDistance != CGFloat(0.0) {
            let userInfo = ["message": totalDistance];
            // Get label node from scene and store it for use later
            self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
            if let label = self.label {
                 label.text = totalDistance.description
                 label.alpha = 1.0
                 label.run(SKAction.fadeIn(withDuration: 2.0))
            }
            }
            totalDistance = CGFloat(0.0)
        } else if contact.bodyB.node?.name == "obstacle" {
            totalDistance = pow(totalDistance,0.5)
            if totalDistance != CGFloat(0.0) {
           // Get label node from scene and store it for use later
            self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
            if let label = self.label {
                label.text = totalDistance.description
                label.alpha = 1.0
                label.run(SKAction.fadeIn(withDuration: 2.0))
            }
        }
            totalDistance = CGFloat(0.0)
        } else if ((contact.bodyA.node?.position.x)! < CGFloat(100.0) && (contact.bodyA.node?.position.y)! < CGFloat(100.0) && (contact.bodyA.node?.position.x)! > CGFloat(0.0) && (contact.bodyA.node?.position.y)! > CGFloat(0.0)) {
            totalDistance = pow(totalDistance,0.5)
            if totalDistance != CGFloat(0.0) {
            // Get label node from scene and store it for use later
            self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
            if let label = self.label {
                label.text = totalDistance.description
                label.alpha = 1.0
                label.run(SKAction.fadeIn(withDuration: 2.0))
            }
        }
            totalDistance = CGFloat(0.0)
        } else if (penUp) {
            lastX = (contact.bodyA.node?.position.x)!
            lastY = (contact.bodyA.node?.position.y)!
            penUp = false;
        } else {
            totalDistance += (((contact.bodyA.node?.position.x)! - lastX) * ((contact.bodyA.node?.position.x)! - lastX))
            totalDistance += (((contact.bodyA.node?.position.y)! - lastY) * ((contact.bodyA.node?.position.y)! - lastY))
            lastX = (contact.bodyA.node?.position.x)!
            lastY = (contact.bodyA.node?.position.y)!
            print(totalDistance)
        }
    }

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        penUp = true;
        if 1 == 2 {
        if let anobstacleNode = self.childNode(withName: "ourobstacle") as? SKSpriteNode {
            anobstacle = anobstacleNode
            if let atextureNode = self.childNode(withName: "rocket") as? SKTexture {
                let rocketAnimation = SKAction.animate(with: [atextureNode],
                                                       timePerFrame: 0.1)
                
                anobstacle.run(rocketAnimation)
            }
            //init slowCar
            anobstacle.physicsBody = SKPhysicsBody(rectangleOf:  CGSize(width: 10, height: 10))
            anobstacle.physicsBody?.categoryBitMask = slowCarCategory
            anobstacle.physicsBody?.collisionBitMask = carCategory
            anobstacle.physicsBody?.contactTestBitMask = carCategory
            anobstacle.name = "nonball"
            anobstacle.physicsBody?.isDynamic = false
            self.addChild(anobstacle)
            
        }
        }
        
        //if let label = self.label {
        //    label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
        //}
        
        for t in touches {
            
            self.makeSpinny(at: t.location(in: self), color: SKColor.green)
            self.lightWithFinger(at: t.location(in: self))
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
            self.makeSpinny(at: t.location(in: self), color: SKColor.blue)
            self.lightWithFinger(at: t.location(in: self))
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        penUp = true;
        for t in touches {
            self.makeSpinny(at: t.location(in: self), color: SKColor.red)
            self.lightWithFinger(at: t.location(in: self))
        }
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        penUp = true;
        for t in touches {
            self.makeSpinny(at: t.location(in: self), color: SKColor.red)
            self.lightWithFinger(at: t.location(in: self))
        }
    }
    
   
}
#endif

#if os(OSX)
// Mouse-based event handling
extension GameScene {

    override func mouseDown(with event: NSEvent) {
        penUp = true;
        if let label = self.label {
            label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
        }
        self.makeSpinny(at: event.location(in: self), color: SKColor.green)
        self.lightWithFinger(at: t.location(in: self))
    }
    
    override func mouseDragged(with event: NSEvent) {
        self.makeSpinny(at: event.location(in: self), color: SKColor.blue)
        self.lightWithFinger(at: t.location(in: self))
    }
    
    override func mouseUp(with event: NSEvent) {
        penUp = true;
        self.makeSpinny(at: event.location(in: self), color: SKColor.red)
        self.lightWithFinger(at: t.location(in: self))
    }

}
#endif

