var EHDI = EHDI || Object.create(null);

EHDI.GAME = EHDI.GAME || Object.create(null);

EHDI.GAME.scene = EHDI.GAME.scene || Object.create(null);

EHDI.GAME.scene.GameScene = function() {
	EHDI.aka.Container.call(this);

	this.bg,
	this.player,
	this.pauseBtn,
	this.score,
	this.playerSpeed,
	this.stagesPassed = 0,
	this.initialDifficulty = 1,
	this.difficulty = this.initialDifficulty,
	this.backDrop,
	this.updateFunc,
	this.isPaused = false,
	this.overlay,
	this.super = EHDI.aka.Container,
	this.allowed = true,
	this.keyUp,
	this.keyDown,
	this.isGameOver = false,
	this.gameOverTimer = new EHDI.GAME.Timer(null, 0),
	this.keyDownHide = false,
	this.mouseDownHide = false,
	this.touches = [],
	this.interactable = true;

	this.gameEvents = {
		pause: "PAUSE",
		restart: "RESTART",
		gameOver: "GAMEOVER"
	};

	EHDI.GAME.gameScene = EHDI.GAME.gameScene || Object.create(null);
	EHDI.GAME.gameScene.endGame = this.gameOver.bind(this);

	for(var i in this.gameEvents) {
		EHDI.GAME.eventManager.register(this.gameEvents[i]);
	}

	EHDI.GAME.eventManager.addListener(this.gameEvents["pause"], this.pause.bind(this));
	EHDI.GAME.eventManager.addListener(this.gameEvents["restart"], this.reset.bind(this));
	EHDI.GAME.eventManager.addListener(this.gameEvents["gameOver"], this.gameOver.bind(this));

	// namespacing
	EHDI.GAME.ObjectManager = EHDI.GAME.ObjectManager || EHDI.GAME.Managers.ObjectManager.getInstance();
	EHDI.GAME.SpriteManager = EHDI.GAME.SpriteManager || EHDI.GAME.Managers.SpriteManager.getInstance();
	EHDI.GAME.GuardManager = EHDI.GAME.GuardManager || EHDI.GAME.Managers.GuardManager.getInstance();
	EHDI.GAME.LevelBuilder = EHDI.GAME.LevelBuilder || EHDI.GAME.Map.LevelBuilder.getInstance();
}

EHDI.GAME.scene.GameScene.prototype = Object.create(EHDI.aka.Container.prototype);

EHDI.GAME.scene.GameScene.prototype.update = function(dt) {
	if(this.pauseBtn.isPaused) {
		this.pause(true);
		if(!this.player.tlHide.paused()) this.player.tlHide.pause();
		this.player.footsteps.paused = true;
	} else {
		if(this.isPaused){
			this.pause(false);
			if(this.player.tlHide.paused()) this.player.tlHide.resume();
			this.player.footsteps.paused = false;
		}
	}
	if(this.player.isDead) {
		if(!this.isGameOver)
			this.setupGameOver();
	}
	if(!this.player.isInScreen()) {
		this.backDrop.alpha = 1;
		this.difficulty += 1;
		this.stagesPassed++;
		this.bg.switch();
		this.resetGameObjects();
		this.backDrop.alpha = 0;
		this.score.updateScore();
		this.score.updateTime(this.computeTime());
	}

	if(!this.isPaused) {
    dragonBones.WorldClock.clock.advanceTime(dt * 0.001);
		EHDI.GAME.GuardManager.update(this.player, dt);
		if(!this.player.isDead && !this.player.hiding) {
			this.player.move(this.playerSpeed, dt);
		}
	}
}

EHDI.GAME.scene.GameScene.prototype.screenWillAppear = function() {
	this.backDrop = new EHDI.aka.Graphics();
	this.backDrop.beginFill(0x000000, 0);
	this.backDrop.drawRect(0, 0, EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight());
	this.backDrop.endFill();

	this.bg = new EHDI.GAME.components.Background();
	this.addChild(this.bg);
	this.player = new EHDI.GAME.components.Player(this);
	this.playerSpeed = this.player.movementSpeed;

  this.pauseBtn = new EHDI.components.pauseButton();

	this.overlay = new EHDI.aka.Graphics();
	this.overlay.beginFill(0x000000, 0.5);
	this.overlay.drawRect(0, 0, EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight());
	this.overlay.endFill();
	this.overlay.visible = false;

	this.interactive = true;
	this.on("mousedown", this.onMouseDown.bind(this));
	this.on("mouseup", this.onMouseUp.bind(this));
	this.on("mouseupoutside", this.onMouseUp.bind(this));
	this.on("touchstart", this.onTouchStart.bind(this));
	this.on("touchend", this.onTouchEnd.bind(this));
	this.on("touchendoutside", this.onTouchEnd.bind(this));

	this.keyUp = this.onKeyUp.bind(this);
	this.keyDown = this.onKeyDown.bind(this);

	document.addEventListener("keyup", this.keyUp);
	document.addEventListener("keydown", this.keyDown);

	EHDI.GAME.LevelBuilder.generateLevel(this, this.difficulty);
}

EHDI.GAME.scene.GameScene.prototype.screenDidAppear = function() {
	EHDI.GAME.utils.bringToFront(this.player.getSprite());

	EHDI.GAME.GuardManager.pauseGuards();

	this.addChild(this.backDrop);
	this.addChild(this.overlay);
	this.addChild(this.pauseBtn);

	var startGame = function(){
		this.score = new EHDI.GAME.components.Score(this);
		EHDI.GAME.GuardManager.startGuards();
		this.score.timer.timeLeft = this.computeTime();

		this.updateFunc = this.update.bind(this);
		EHDI.GAME.updateManager.addFrameListener(this.updateFunc);
	}.bind(this);

	if(EHDI.GAME.saveData.isFirstTimePlay){
		var htp = new EHDI.popup.HTPPopUp(startGame);
		htp.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5,
		EHDI.GAME.sceneManager.getStageHeight() * 0.5);
		EHDI.GAME.sceneManager.pushPopUp(htp,
		{alpha : new EHDI.scene.TransitionParameter(0, 1), duration : 0.1});
	}else{
		startGame();
	}
}

EHDI.GAME.scene.GameScene.prototype.screenWillDisappear = function() {
	EHDI.GAME.updateManager.removeFrameListener(this.updateFunc);
}

EHDI.GAME.scene.GameScene.prototype.screenDidDisappear = function() {
	document.removeEventListener("keyup", this.keyUp);
	document.removeEventListener("keydown", this.keyDown);

	this.pauseBtn.endGame();
	this.pauseBtn.dispose();
	this.score.timer.dispose();
	EHDI.GAME.updateManager.removeFrameListener(this.updateFunc);
	EHDI.GAME.soundManager.pauseBGM();

	this.player.destroyAllArmature();

	TweenMax.killAll();
  EHDI.GAME.soundManager.stopAllSFX();
	EHDI.GAME.soundManager.stopBGM();

	EHDI.GAME.ObjectManager.removeActiveObjects(this);
	EHDI.GAME.GuardManager.removeActiveGuards(this, true);
	this.super.prototype.destroy.call(this, {children: true});
}

EHDI.GAME.scene.GameScene.prototype.hidePlayer = function() {
	if(!this.allowed || this.player.isDead)
		return;

	this.playerSpeed = 0;
	this.player.hideIn();
	this.allowed = false;
}

EHDI.GAME.scene.GameScene.prototype.unhidePlayer = function() {
	if(this.keyDownHide || this.mouseDownHide || this.isPaused || this.player.isDead)
		return;

	this.allowed = true;
	this.playerSpeed = this.player.movementSpeed;
	this.player.hideOut();
}

EHDI.GAME.scene.GameScene.prototype.onMouseUp = function(event) {
	this.mouseDownHide = false;
	this.unhidePlayer();
}

EHDI.GAME.scene.GameScene.prototype.onMouseDown = function(event) {
	if(!event.target.interactable)
		return;

	this.mouseDownHide = true;
	this.hidePlayer();
}

EHDI.GAME.scene.GameScene.prototype.onKeyUp = function(event) {
	if(event.keyCode == 32) {
		this.keyDownHide = false;
		this.unhidePlayer();
	}
}

EHDI.GAME.scene.GameScene.prototype.onKeyDown = function(event) {
	if(event.keyCode == 32) {
		this.keyDownHide = true;
		this.hidePlayer();
	}
}

EHDI.GAME.scene.GameScene.prototype.onTouchStart = function(event) {
	if(!event.target.interactable)
		return;

	this.touches.push(event);
	this.hidePlayer();
}

EHDI.GAME.scene.GameScene.prototype.onTouchEnd = function(event) {
	this.touches.pop();
	if(this.touches.length == 0) {
		this.unhidePlayer();
	}
}

EHDI.GAME.scene.GameScene.prototype.resetGameObjects = function() {
	this.player.resetPosition();
	EHDI.GAME.ObjectManager.removeActiveObjects(this);
	EHDI.GAME.GuardManager.removeActiveGuards(this);
	EHDI.GAME.LevelBuilder.generateLevel(this, this.difficulty);
	EHDI.GAME.utils.bringToFront(this.player.getSprite());
}

EHDI.GAME.scene.GameScene.prototype.reset = function(event) {
	EHDI.GAME.updateManager.removeFrameListener(this.updateFunc);
	EHDI.GAME.updateManager.addFrameListener(this.updateFunc);
	this.overlay.visible = false;
	this.difficulty = this.initialDifficulty;
	this.stagesPassed = 0;
	this.player.isDead = false;
	this.playerSpeed = this.player.movementSpeed;
	this.resetGameObjects();
	this.score.resetScore();
}

EHDI.GAME.scene.GameScene.prototype.setupGameOver = function() {
	this.isGameOver = true;
	this.playerSpeed = 0;
	this.score.timer.dispose();
	EHDI.GAME.GuardManager.pauseGuards();
	this.gameOverTimer = new EHDI.GAME.Timer(EHDI.GAME.eventManager.dispatch.bind(null, this.gameEvents.gameOver), 2000);
}

EHDI.GAME.scene.GameScene.prototype.gameOver = function() {
	var highScore = EHDI.GAME.HIGH_SCORE || 0;

	this.pauseBtn.endGame();
	//this.pauseBtn.dispose();

	if(highScore <= this.score.val)
		EHDI.GAME.HIGH_SCORE = this.score.val;

	var stars = 0;
	if(this.score.val < 250 && this.score.val > 100)
		stars = 1;
	else if(this.score.val >= 250 && this.score.val <= 500)
		stars = 2;
	else if(this.score.val > 500)
		stars = 3;

	EHDI.GAME.GuardManager.pauseGuards();
  	EHDI.GAME.updateManager.removeFrameListener(this.score.timer.timerUpdate);
	EHDI.GAME.updateManager.removeFrameListener(this.updateFunc);
	/*
	var popup = new EHDI.popup.PostGamePopUp( stars, this.score.val );
	popup.x = EHDI.GAME.sceneManager.getStageWidth() * 0.5;
	popup.y = EHDI.GAME.sceneManager.getStageHeight() * 0.5;
	EHDI.GAME.sceneManager.pushPopUp( popup );
	popup.highscoreText.text = "High Score: " + EHDI.GAME.HIGH_SCORE;
	*/
	if(this.score.val > EHDI.GAME.saveData.highScore) {
        EHDI.GAME.saveData.highScore = this.score.val;
        EHDI.sbGame.saveGameData(EHDI.GAME.saveData, "DEFAULT", function(){
            console.log("data saved.");
        });
    }
    EHDI.sbGame.end(this.score.val);
}

EHDI.GAME.scene.GameScene.prototype.pause = function(val) {
	if(val) {
		this.playerSpeed = 0;
		EHDI.GAME.GuardManager.pauseGuards();
		this.gameOverTimer.pause();
	} else {
		EHDI.GAME.GuardManager.startGuards(true);
		this.gameOverTimer.start();
	}

	this.overlay.visible = val;
	this.isPaused = val;

	if(!this.keyDownHide) {
		this.unhidePlayer();
	}
}

EHDI.GAME.scene.GameScene.prototype.computeTime = function() {
	return (EHDI.GAME.GuardManager.activeGuardCount()+2)*15;
}