var WordFlyingSaucer = {

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

		sessionStorageManager.setIsNewAppHighestRecord(false);

		this.initVariables();


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

		this.scoreManager = new ScoreManager();
		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.heartManager = new HeartManager();
		this.heartManager.addOnChangeGameOverListener(
			(function() { this.gameOver(); }).bind(this)
		);

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


		// game stage
		this.drawBackground();

		this.flyingsaucers = [];
		for(var i = 0; i < WordFlyingSaucer.MAX_FLYINGSAUCER_COUNT; i++) {
			this.flyingsaucers[i] = new FlyingSaucer(i);
			this.flyingsaucers[i].setScoreManager(this.scoreManager);
			this.flyingsaucers[i].setHeartManager(this.heartManager);
			this.flyingsaucers[i].setExtractWordManager(this.extractWordManager);
			this.flyingsaucers[i].setGameLevelManager(this.gameLevelManager);
			// this.flyingsaucers[i].startAttack();
		}

		this.centerMessageText = new CenterMessageText();

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

		this.scoreBoard = new ScoreBoard();

		var heartGauge = new HeartGauge(this.heartManager);
		heartGauge.start();


		// input text
		var INPUT_TEXT_Y = 680;
		this.inputText = new InputTypeText(game.world.centerX, INPUT_TEXT_Y);
		this.inputText.anchor.set(0.5);
		this.inputText.canvasInput.value('');
		this.inputText.canvasInput.focus();
		this.inputText.canvasInput.fontSize(26);
		this.inputText.canvasInput.placeHolder("입력 후 Space, Enter키를 누르세요");
		// inputText.canvasInput._onkeydown = this.checkInputText;
		// inputText.canvasInput._onkeyup = function() {
		var self = this;
		this.inputText.canvasInput._onkeyup = function() {
			self.checkTypingContents(event);
		}


		// bottom ui
		this.screenBottomUI = new ScreenBottomUI();
		// screenBottomUI.printBottomUILeftText("");
		this.screenBottomUI.printCenterText(sessionStorageManager.getPlayingAppKoreanName());
		this.screenBottomUI.printRightText(sessionStorageManager.getPlayerName());


		this.startGame();
	},


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


	initVariables: function() {
		this.extractWordManager = new ExtractWordManager();
		this.gameLevelManager = new GameLevelManager(this);
		this.gameLevelManager.setExtractWordManager(this.extractWordManager);

		this.speedLevel = 0;

		this.tileSprite = null;
	},

	drawBackground: function() {
		this.game.stage.backgroundColor = "#000000";	// '#4d4d4d';


		var bmd = game.add.bitmapData(GAME_SCREEN_SIZE.x, GAME_SCREEN_SIZE.y);
		bmd.addToWorld();

		var y = 200;
		var GRADIATION_HEIGHT = 5;
		var GRADIATION_COUNT = 50;
		for(var i = 0; i < GRADIATION_COUNT; i++) {
			var c = Phaser.Color.interpolateColor(
				WordFlyingSaucer.COLOR_ATMOSPHERE_OUTSIDE,
				WordFlyingSaucer.COLOR_ATMOSPHERE_INSIDE,
				GRADIATION_COUNT, i
			);
			bmd.rect(0, y, GAME_SCREEN_SIZE.x, y + GRADIATION_HEIGHT, Phaser.Color.getWebRGB(c));
			y += GRADIATION_HEIGHT;
		}

		var GRADIATION_HEIGHT = 10;
		var GRADIATION_COUNT = 10;
		for(var i = 0; i < GRADIATION_COUNT; i++) {
			var c = Phaser.Color.interpolateColor(
				WordFlyingSaucer.COLOR_ATMOSPHERE_INSIDE,
				WordFlyingSaucer.COLOR_ATMOSPHERE_HORIZON,
				GRADIATION_COUNT, i
			);
			bmd.rect(0, y, GAME_SCREEN_SIZE.x, y + GRADIATION_HEIGHT, Phaser.Color.getWebRGB(c));
			y += GRADIATION_HEIGHT;
		}

		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');
		}

		var GROUND_OFFSET_Y	= 600;
		this.tileSprite = game.add.tileSprite(
			GAME_SCREEN_SIZE.x, GAME_SCREEN_SIZE.y - 50,
			GAME_SCREEN_SIZE.x, 100,
			"tile_choco");
		this.tileSprite.anchor.set(0.5);
		this.tileSprite.tileScale.set(2);
	},

	startGame: function() {
		this.showLevelUpText(this.gameLevelManager.getWordLevel());	// initial wordLevel = 0;

		var startIndexList = [];
		for(var i = 0; i < WordFlyingSaucer.MAX_FLYINGSAUCER_COUNT; i++)
			startIndexList.push(i);
		this.randomStartIndex = 0;
		this.randomStartIndexList = Phaser.ArrayUtils.shuffle(startIndexList);

		for(var i = 0; i < this.randomStartIndexList.length; i++) {
			var randomDelayTime = Phaser.Timer.SECOND * 2 * i + Math.random() * Phaser.Timer.SECOND;
			game.time.events.add(randomDelayTime, this.waitAndStartAttack, this);
		}
	},

	waitAndStartAttack: function() {
		var index = this.randomStartIndexList[this.randomStartIndex];
		this.flyingsaucers[index].startAttack();
		this.randomStartIndex++;
	},

	timeOver: function() {
		var timeOverText = new TimeOverText();

		sessionStorageManager.setRecord(this.scoreManager.getScore());
		if(!isExperienceMaestroAccount())
			this.updateResultRecord();

		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';
	},

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

	stopAndGoResult: function() {
		// remove all flyingsaucers
		var count = this.flyingsaucers.length;
		for(var i = 0; i < count; i++) {
			this.flyingsaucers[i].destroy();
		}

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


	checkTypingContents: function(event) {
		var count = this.flyingsaucers.length;
		if(event.keyCode == Phaser.KeyCode.ENTER || event.keyCode == Phaser.KeyCode.SPACEBAR) {
			// console.log("event.keyCode : " + event.keyCode + "( " + Phaser.KeyCode.SPACEBAR + ")");
			for(var i = 0; i < count; i++) {
				this.flyingsaucers[i].checkWord(this.inputText.canvasInput.value().trim());
			}

			this.inputText.canvasInput.value("");
		} else {

			for(var i = 0; i < count; i++) {
				this.flyingsaucers[i].checkInputText(this.inputText.canvasInput.value());
			}
		}
	},

	showLevelUpText: function(wordLevel) {
		this.centerMessageText.showText(wordLevel, this.gameLevelManager.getWordLevelText(wordLevel));
	},

}


WordFlyingSaucer.MAX_FLYINGSAUCER_COUNT		= 5;

WordFlyingSaucer.COLOR_ATMOSPHERE_OUTSIDE		= 0x000000;
WordFlyingSaucer.COLOR_ATMOSPHERE_INSIDE		= 0x444400;
WordFlyingSaucer.COLOR_ATMOSPHERE_HORIZON		= 0x440000;