//
//  File.swift
//  sleazyburger
//
//  Created by Aslak Gronflaten on 1/25/15.
//  Copyright (c) 2015 Javelin. All rights reserved.
//

import Foundation
import SpriteKit


func amplitude(x : CGFloat, y : CGFloat) -> CGFloat {
    let h = x*x + y*y
    let s = sqrt(h)
    return s
}

class World : SKNode {
    
    var game : Game?
    var zoomed = false
    var scrolling = false
    var timer : NSTimer?
    var toppled = false
    
    var stack : [SKSpriteNode]  = []
    
    func addBurger(burger : SKSpriteNode) {
        if stack.count > 5 {
            stack.removeLast()
            if timer == nil {
                timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "checkFall:", userInfo: nil, repeats: true)
            }
        }
        stack.insert(burger, atIndex: 0)
        self.addChild(burger)
        
        // Check if we need scrolling
        scrollIfNeeded()
    }
    
    let speedLimit : CGFloat = 200.0

    func checkFall(o : AnyObject?) {
        if toppled {
            return
        }
        var falling = 0
        for s in stack {
            if let b = s.physicsBody {
                let v = b.velocity
                let s = amplitude(v.dx, v.dy)
                if s > speedLimit {
//                    println("Piece has speed of \(s) =  \(NSStringFromCGVector(v))");
                    falling++
                }
            }
        }
        if falling > 2 {
            toppled = true
            println("Tower is toppling!")
            zoomOut()
            

/*
            let sc = CGFloat(300.0) / -position.y + CGFloat(300.0)
            runAction(SKAction.scaleTo(sc, duration: 0.1))
            runAction(SKAction.moveToY(0, duration: 0.1))
*/
            // TODO Fix the zoom

        }
    }
    
    func zoomOut() {
        removeAllActions()
        let speed : NSTimeInterval = 0.1
 //       runAction(SKAction.moveToY(40.0, duration: speed))
        runAction(SKAction.moveTo(CGPointMake(225.0, 40), duration: speed))
        runAction(SKAction.scaleTo(0.2, duration: speed)) {
            self.runAction(SKAction.waitForDuration(3.0)) {
                if let g = self.game {
                    g.outro()
                }
            }

        }


    }
    
    func scrollIfNeeded() {
        // If this burger bit is too high, scroll world down.
        var last : CGFloat = 0
        var count = 0
        var removals : [Int] = []
        if stack.count > 5 {
            for i in reverse(2...5) {
                let b = stack[i]
                let y = b.position.y
                if y < last {
                    println("Burger out of order detected - it probably fell? Removing it...")
                    stack.removeAtIndex(i)
                    scrollIfNeeded()
                    return
                } else {
                    last = y
                }
                count++
//                println("Burger \(i) velocity: \(NSStringFromCGVector(b.physicsBody!.velocity))")
            }
        }
        if last > 200 {
            let destY = 200-last
            self.removeAllActions()
            self.runAction(SKAction.moveToY(destY, duration: 0.5)) {
                
            }
        
        }
    }
    
}
