var Game = {

	create: function() {
		this.dbConnectManager = new DBConnectManager();
		sessionStorageManager.setRecord(0);

		this.game.stage.backgroundColor = "#000000";	// '#4d4d4d';

		sessionStorageManager.setIsNewAppHighestRecord(false);

		// keyboard shortcut
		this.keyboardShortcut = new KeyboardShortcut();
		this.keyboardShortcut.addCallback(
			Phaser.KeyCode.ESC,	// keyCode
			null,	// keyDownHandler
			(function() { this.back(); }).bind(this),	// keyUpHandler
			"card matching"	// callerClassName
		);

		// top ui
		var screenTopUI = new ScreenTopUI();
		screenTopUI.makeBackButton( (function() { this.back(); }).bind(this) );
		screenTopUI.makeFullScreenButton();

		this.scoreManager = new ScoreManager();
		this.scoreBoard = new ScoreBoard();
		this.scoreManager.addOnChangeScoreListener(
			(function(score) {
				sessionStorageManager.setRecord(score);
				this.scoreBoard.printScore(NumberUtil.numberWithCommas(score));
			}).bind(this)
		);
		this.scoreManager.addOnChangeHighScoreListener(
			(function(highScore) {
				// console.log(highScore);
				// sessionStorageManager.setAppHighestRecord(highScore);
				sessionStorageManager.setIsNewBestRecrd(true);
				// this.screenBottomUI.printLeftTextWithAppHighestRecord(sessionStorageManager.getAppHighestRecord());
			}).bind(this)
		);

		this.setClickEnable(false);
		this.stageTimer = new StageTimer(
			Game.GAME_TIME_SEC,
			(function() {
				this.setClickEnable(false);
				this.timeOver();
			}).bind(this)
		);

		this.initVariables();


		// game stage
		game.stage.backgroundColor = '#4d4d4d';
		graphics = game.add.graphics(0, 0);

		this.plusScoreGroup = game.add.group();

		var table = game.add.tileSprite(0, 340, GAME_SCREEN_SIZE.x, 660, 'wooden_table');
		this.meatPlate = game.add.image(220, Game.MEAT_PLATE_POSITION_Y, 'plate');
		this.meatPlate.anchor.set(0.5);
		this.meatPlate.smoothed = false;

		this.heatPlate = game.add.image(game.world.centerX, Game.HEAT_PLATE_POSITION_Y, 'heat_plate');
		this.heatPlate.anchor.set(0.5);
		this.heatPlate.smoothed = false;
		this.heatPlate.scale.set(1);

		this.god = new God(game.world.width - 120, Game.GOD_POSITION_Y + 100, this);

		// meat
		this.meatGroup = game.add.group();
		for(var i = 0; i < Game.MAX_MEAT_COUNT; i++) {
			var meat = new Meat(this);
			meat.name = "meat" + i;
			meat.setActive(false, -100, -100, "");
			this.meatGroup.add(meat);
		}

		// speech bubble
		this.speechBubble = new SpeechBubble(game.world.centerX + 100, game.world.centerY - 160);
		this.speechBubble.hideSpeechBubble();


		var experienceAppTimer = new ExperienceAppTimer();
		experienceAppTimer.setTimeOverListener(
			(function() { this.timeOver(); }).bind(this)
		);


		// bottom ui
		var screenBottomUI = new ScreenBottomUI();
		screenBottomUI.printLeftTextWithAppHighestRecord(sessionStorageManager.getAppHighestRecord());
		screenBottomUI.printCenterText(sessionStorageManager.getPlayingAppKoreanName());
		screenBottomUI.printRightText(sessionStorageManager.getPlayerName());


		this.startGame();
		// // this.countDown();
	},

	initVariables: function() {
		this.playingStageNo;
		this.activatedMeatCount;
		this.clearedMeatCount;

		this.plusScoreTextGroup;

		this.timeEvent;
		this.gameTimeEvents = [];

		this.meatCount;
		this.badMeatCount = 0;
	},



	back: function() {
		sessionStorageManager.resetPlayingAppData();
		location.href = '../../web/client/main_menu.html';
	},

	/*
	countDown: function() {
		var style = { font: "bold 200px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" };
		this.countDownText = game.add.text(0, 0, "", style);
		this.countDownText.setTextBounds(0, 0, game.world.width, game.world.height);
		this.countDownText.stroke = "#333";
		this.countDownText.strokeThickness = 50;

		this.countDownNumber = 3;
		if(isDebugMode())
			this.countDownNumber = 1;
		this.tweenCountDown();
	},

	tweenCountDown: function() {
		if(this.countDownNumber === 0) {
			this.startGame();
			return;
		}

		this.countDownText.text = this.countDownNumber.toString();
		this.countDownText.alpha = 1;

		var countDownTween = game.add.tween(this.countDownText);
		countDownTween.to( { alpha: 0 }, 1000, Phaser.Easing.Linear.None, true);
		countDownTween.onComplete.add(this.tweenCountDown, this);

		this.countDownNumber--;
	},
	*/

	startGame: function() {
		this.playingStageNo = 1;

		this.startStage();
		this.stageTimer.start();

	},

	startStage: function() {
		this.clearedMeatCount = 0;
		this.badMeatCount = 0;
		this.activatedMeatCount = this.getStageMeatCount();
		this.serveMeats();
	},

	setClickEnable: function(value) {
		this.isEnableClick = value;
	},

	getStageMeatCount: function() {
		this.activatedMeatCount = this.playingStageNo + 2;
		return this.activatedMeatCount;
	},

	serveMeats: function() {
		for(var i = 0; i < Game.MAX_MEAT_COUNT; i++) {
			var meat = this.meatGroup.children[i];
			meat.setActive(false, -100, -100, "");
		}

		for(var i = 0; i < this.activatedMeatCount; i++) {
			var meat = this.meatGroup.children[i];
			var randX = this.meatPlate.x - game.rnd.integerInRange(-100, 100);
			var randY = this.meatPlate.y - game.rnd.integerInRange(-30, 30);
			meat.setActive(true, randX, randY, "");
		}
	},

	getScore: function() {
		return this.playingStageNo * 10;
	},

	getBonusTime: function() {
		if(this.badMeatCount > 0)
			return 0;

		if(this.playingStageNo == 1)
			return 5;
		else if(this.playingStageNo == 2)
			return 7;
		else
			return 6 + this.playingStageNo;
	},



	isOverHeatPlate: function(x, y, width, height) {
		var plateHalfWidth = (this.heatPlate.width - Game.HEAT_PLATE_HANDLE_WIDTH) / 2;
		var plateHalfHeight = this.heatPlate.height / 2;

		if(x < this.heatPlate.x - plateHalfWidth) {
			return false;
		} else if(this.heatPlate.x + plateHalfWidth < x) {
			return false;
		} else if(y < this.heatPlate.y - plateHalfHeight + Game.HEAT_PLATE_START_OFFSET_Y) {
			return false;
		} else if(this.heatPlate.y + plateHalfHeight + Game.HEAT_PLATE_START_OFFSET_Y - Game.HEAT_PLATE_HEIGHT< y) {
			return false;
		}

		return true;
	},

	isOverGod: function(x, y, width, height) {
		// console.log("isOverGod : " + x + ", " + y + ", " + width + ", " + height);

		var godHalfWidth = (this.god.width - Game.GOD_OUT_OF_FACE_WIDTH) / 2;
		var godHalfHeight = this.god.height / 2;
		if(x < this.god.x - godHalfWidth) {
			return false;
		} else if(this.god.x + godHalfWidth < x) {
			return false;
		} else if(y < this.god.y - this.god.height + Game.GOD_OUT_OF_FACE_HEIGHT) {
			return false;
		} else if(this.god.y - Game.GOD_OUT_OF_FACE_HEIGHT < y) {
			return false;
		}

		return true;
	},

	godEatMeat: function(meat) {
		// console.log("isOverGod : " + x + ", " + y + ", " + width + ", " + height);

		// console.log("god eat : " + meat);
		// console.log("meat grade : " + meat.getMeatGrade());

		if(meat.getMeatGrade() == Meat.DONENESS_WELLDONE) {
			this.god.animateHappy(Meat.DONENESS_WELLDONE);	// "맛있어♥♡♥");

			var score = this.getScore();
			this.scoreManager.plusScore(score);

			var tempPlusScore = new PlusScore(this.god.x, this.god.y - 180, score);
			this.plusScoreGroup.add(tempPlusScore);
		} else {
			this.badMeatCount++;

			if(meat.getMeatGrade() == Meat.DONENESS_RARE) {
				this.god.animateAngry(Meat.DONENESS_RARE);	// "날고기 싫어!!!");
			} else {	// Meat.DONENESS_BURN_BLACK
				this.god.animateAngry(Meat.DONENESS_BURN_BLACK);	// "탄 고기 안먹어!!!");
			}
		}

		meat.setActive(false, -100, -100, '');
		this.clearedMeatCount++;
		if(this.clearedMeatCount == this.activatedMeatCount) {
			this.clearStage();
		}
	},

	clearStage: function() {
		this.stageTimer.addBonusTime(this.getBonusTime());

		this.playingStageNo++;

		var startStageTimeEvent = game.time.events.add(Phaser.Timer.SECOND * 1, this.startStage, this);
		this.gameTimeEvents[this.gameTimeEvents.length + 1] = startStageTimeEvent;
	},



	animateTextAlpha: function(targetText, startAlpha, endAlpha, msTime, effectType) {
		targetText.alpha = startAlpha;
		game.add.tween(targetText).to({alpha: endAlpha}, msTime, effectType, true);
	},


	timeOver: function() {
		var timeOverText = new TimeOverText();
		if(!isExperienceMaestroAccount())
			this.updateResultRecord();
		this.stopAndGoResult();
	},

	stopAndGoResult: function() {
		for(var i = 0; i < this.gameTimeEvents.length; i++) {
			game.time.events.remove(this.gameTimeEvents[i]);
		}
		this.gameTimeEvents = [];

		for(var i = 0; i < Game.MAX_MEAT_COUNT; i++) {
			this.meatGroup.children[i].hide();
		}

		game.time.events.add(Phaser.Timer.SECOND * 2, this.goResult, this);
	},

	updateResultRecord: function() {
		if(sessionStorageManager.getMaestroAccountType() < 100) {	// experience account
			this.dbConnectManager.updateResultRecord(
				sessionStorageManager.getMaestroID(),
				sessionStorageManager.getPlayerID(),
				sessionStorageManager.getPlayingAppID(),
				sessionStorageManager.getRecord()
			);
		}
	},

	goResult: function() {
		location.href = '../../web/client/result.html';
	},

}


Game.GAME_TIME_SEC				= 60;
Game.NEXT_STAGE_DELAY_MS		= 500;

Game.MAX_MEAT_COUNT				= 20;

Game.HEAT_PLATE_HANDLE_WIDTH	= 440;
Game.HEAT_PLATE_START_OFFSET_Y	= 80;
Game.HEAT_PLATE_HEIGHT			= 220;

Game.GOD_OUT_OF_FACE_WIDTH		= 30;
Game.GOD_OUT_OF_FACE_HEIGHT		= 30;

Game.MEAT_PLATE_POSITION_Y		= 360;
Game.GOD_POSITION_Y				= 240;
Game.HEAT_PLATE_POSITION_Y		= GAME_SCREEN_SIZE.y / 2 + 220;
