var Game = {

	// preload: function() {
	// 	game.stage.disableVisibilityChange = true;
	// },

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

		game.physics.enable(this, Phaser.Physics.ARCADE);

		this.indexMissile = 0;

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

		sessionStorageManager.setIsNewAppHighestRecord(false);

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

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

		// game stage
		var stars = game.add.group();
		for (var i = 0; i < 128; i++) {
			var randomY = game.rnd.integerInRange(60, GAME_SCREEN_SIZE.y - 80);
			stars.create(game.world.randomX, randomY, 'star');
		}



		// contents
		this.spaceship = new Spaceship();

		this.missiles = [];
		for(var i = 0; i < Game.MAX_MISSILE_COUNT; i++) {
			var alien = new Missile(this.spaceship,
				(function() {
					this.spaceship.alpha = 0;
					this.spaceship.body.enable = false;
					this.showExplosionParticle();

					this.gameOver();
				}).bind(this)	// onCollisionHandler
			);
			this.missiles.push(alien);
		}


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

		this.stopWatch = new StopWatch(game);


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


		// this.startGame();

		this.countDown();
		this.spaceship.setActive(true);
	},


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

	countDown: function() {
		var style = { font: "bold 200px Arial", fill: "#fff", wordWrap: true, wordWrapWidth: game.world.centerX, align: "center" };
		this.countDownText = game.add.text(game.world.centerX, game.world.centerY, "", style);
		// this.countDownText.setTextBounds(0, 0, game.world.width, game.world.height);
		this.countDownText.anchor.set(0.5);
		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.stopWatch.start();
		this.timerCount = 0;
		this.timerEvent = game.time.events.loop(Phaser.Timer.SECOND, this.updateTimer, this);
	},

	updateTimer: function() {
		var every5sec = this.timerCount % 5;
		if(every5sec == 0) {
			var waveNo = this.timerCount / 5;
			this.sendWave(waveNo);
		}

		this.timerCount++;
	},

	sendWave: function(waveNo) {
		// console.log("*** " + waveNo + " ***");
		if(this.indexMissile >= Game.MAX_MISSILE_COUNT)
			return;

		var beginAlienIndex = waveNo * 5;
		var endAlienIndex = (waveNo + 1) * 5;
		for(this.indexMissile = beginAlienIndex; this.indexMissile < endAlienIndex; this.indexMissile++) {
			if(this.indexMissile > Game.MAX_MISSILE_COUNT) {
				this.indexMissile = Game.MAX_MISSILE_COUNT;
				return;
			}

			this.missiles[this.indexMissile].setActive(true);
			// console.log(this.indexMissile);
		}
	},

	timeOver: function() {
		this.spaceship.alpha = 0;
		this.spaceship.body.enable = false;
		this.showExplosionParticle();

		var timeOverText = new TimeOverText();
		this.stopAndGoResult();
	},

	gameOver: function() {
		var gameOverText = new GameOverText();
		this.stopAndGoResult();
	},

	stopAndGoResult: function() {
		var recordTime = this.stopWatch.stop();
		sessionStorageManager.setRecord(recordTime);
		if(!isExperienceMaestroAccount())
			this.updateResultRecord();

		game.time.events.add(Game.GAME_OVER_WAIT_TIME_MS, 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';
	},

	showExplosionParticle: function() {
		var hitStarEmitter = game.add.emitter(
			this.spaceship.x,
			this.spaceship.y,
			10
		);
		hitStarEmitter.makeParticles('star');
		hitStarEmitter.minParticleScale = 1;
		hitStarEmitter.maxParticleScale = 3;
		hitStarEmitter.forEach(
			function(particle) {
				// particle.tint = 0xadff2f;
				particle.tint = 0xffa5a5;
			}
		);
		hitStarEmitter.gravity = 0;
		hitStarEmitter.start(true, 1000, null, 100);
	}

}

Game.GAME_OVER_WAIT_TIME_MS		= 3000;

Game.MAX_MISSILE_COUNT			= 100;