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

import UIKit
import AVFoundation
import SpriteKit

class MiniGame: UIViewController {
    var excitement : CGFloat = 0.0
    var stage = 0
    var done = false
    var timer : NSTimer?
    var overlay : UIImageView?
    
    @IBOutlet weak var guy: UIImageView!
    @IBOutlet weak var grayScale: UIImageView!
    @IBAction func pan(p: UIPanGestureRecognizer) {
        switch p.state {
            case .Changed:
//                println("vel=\(p.velocityInView(view))")
                stroke(p.velocityInView(view))
            default:
                // Stopped ?  Cool off
                break
        }
    }
    @IBAction func quit(sender: AnyObject) {
        //self.navigationController?.popViewControllerAnimated(true)
        performSegueWithIdentifier("scoring", sender: self)
    }
    
    override func viewWillAppear(animated: Bool) {
        
        musicPlayer?.stop()
        done = false
        guy.hidden = false
        if let img = grayScale.image?.imageWithRenderingMode(.AlwaysTemplate) {
            grayScale.image = img
        }
        grayScale.tintColor = UIColor.whiteColor()
        stage = 0
        excitement = 0
        if timer == nil {
            timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "bored:", userInfo: nil, repeats: true)
            timer?.tolerance = 0.5
        }

    }
    
    override func viewWillDisappear(animated: Bool) {
        timer?.invalidate()
        timer = nil
    }
    
    func bored(dummy : AnyObject?) {
        excitement -= 0.005
        if excitement < 0 {
            excitement = 0
        } else {
            retint()
        }
    }
    
    func stroke(vel : CGPoint) {
        let s = amplitude(vel.x, vel.y)
        let gain = (s - 1000.0) / 500000.0
        excitement =  excitement + gain

        retint()
        if excitement > 1.0 {
            if !done {
                grayScale.tintColor = UIColor.whiteColor()
//                performSegueWithIdentifier("scoring", sender: self)
                done = true
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

                if let url = NSBundle.mainBundle().URLForResource("pop2", withExtension: "wav") {
                    if let av = AVAudioPlayer(contentsOfURL: url, error: nil) {
                        av.numberOfLoops = 1
                        av.volume = 1.0
                        av.play()
                        println("Played the sound")
                    } else {
                        println("Did not load player")
                    }
                } else {
                    println("Did not find url for sound")
                    }
//                    })

                guy.hidden = true
                timer?.invalidate()
                stickyFace()
                
            }
        }
    }
    
    func stickyFace() {
        let i = UIImageView(image: UIImage(named: "sleazeface.png"))
        self.view.addSubview(i)
        i.opaque = true
        i.alpha = 0.0
        UIView.animateWithDuration(2) {
            i.alpha = 1.0
        }
        overlay = i
        NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: "gotoScore:", userInfo: nil, repeats: false)
    }
    
    func gotoScore(o : AnyObject?) {
        performSegueWithIdentifier("scoring", sender: nil)
    }
    
    func retint() {
        if done {
            return
        }
        let ex = min(excitement, 1.0)
        grayScale.tintColor = UIColor(hue: 11/255, saturation: ex, brightness: 1.0, alpha: 1.0)
//        println("Ex: \(ex)")
    }
}