//
//  GameViewController.swift
//  sleazyburgerpad
//
//  Created by Aslak Gronflaten on 1/23/15.
//  Copyright (c) 2015 Javelin. All rights reserved.
//

import UIKit
import SpriteKit
import AVFoundation
import AVKit

extension SKNode {
    class func unarchiveFromFile(file : NSString) -> SKNode? {
        if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
            var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
            var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
            
            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameSceneIPad
            archiver.finishDecoding()
            return scene
        } else {
            return nil
        }
    }
}

class GameViewController: Common, OutroDelegate {

    @IBOutlet weak var miniGame : MiniGame!
    
    @IBOutlet weak var skView: SKView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    

    func gotoMinigame() {
        performSegueWithIdentifier("minigame", sender: self)
    }
    
    override func viewWillAppear(animated: Bool) {
        musicPlayer?.stop()
        if let scene = GameSceneIPad.unarchiveFromFile("GameScene") as? GameSceneIPad {
            // Configure the view.
//            skView.showsFPS = true
//            skView.showsNodeCount = true
            skView.multipleTouchEnabled = true
            
            /* Sprite Kit applies additional optimizations to improve rendering performance */
  //          skView.ignoresSiblingOrder = true
            
            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill
            
            skView.presentScene(scene)
            scene.game.outroDelegate = self
        }
    }
    
    override func viewDidAppear(animated: Bool) {

    }
    
    override func viewDidDisappear(animated: Bool) {
        if let scene = skView.scene {
            scene.removeAllActions()
            scene.removeAllChildren()
            skView.presentScene(nil)
        }
    }


    override func shouldAutorotate() -> Bool {
        return true
    }

    override func supportedInterfaceOrientations() -> Int {
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
            return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
        } else {
            return Int(UIInterfaceOrientationMask.All.rawValue)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}
