var WhacAMole = {

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

		var self = this;

		this.isOnStage = false;

		this.initTypingData();
		sessionStorageManager.setIsNewAppHighestRecord(false);

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

		game.stage.backgroundColor = '#4d4d4d';

		// 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)
		);

		// var heartManager = new HeartManager();


		this.stageTimer = new StageTimer( WhacAMole.STAGE_TIMER_SEC, (function() {
			self.isOnStage = false;

			// self.goResult();
			self.timeOver();
		}));


		this.bigMole = new BigMole(game.world.centerX, BigMole.START_POS_Y);
		this.hammer = new Hammer();

		// typing content
		var typingContentBG = new TypingContentBG();
		typingContentBG.makeWhacAMoleContentBG();

		var TYPING_CONTENT_Y = 260;

		textStyleBasic.font = "bold 84px Times New Roman";
		this.textTypingContent = game.add.text(game.world.centerX, TYPING_CONTENT_Y, "", textStyleBasic)
		.setShadow(3, 3, 'rgba(0, 0, 0, 1)', 2)
		.addColor(WhacAMole.COLOR_CONTENT_INPUT, 0);
		this.textTypingContent.anchor.set(0.5);

		this.textTypingBracket = game.add.text(game.world.centerX, TYPING_CONTENT_Y, "[      ]", textStyleBasic)
		.setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2)
		.addColor(WhacAMole.COLOR_BRACKET, 0);
		this.textTypingBracket.anchor.set(0.5);


		// textStyleBasic.font = "32px Arial";
		var OFFSET_WORD_X = 70;

		var textDoneColor = [ '#99994d', '#77774d', '#66664d' ];
		this.textTypingContentsDone = [];
		this.helmetDone = [];
		for(var i = 0; i < WhacAMole.TYPING_CONTENT_DONE_COUNT; i++) {
			this.textTypingContentsDone[i] = game.add.text(
				game.world.centerX - 200 - i * OFFSET_WORD_X,
				TYPING_CONTENT_Y,
				"", textStyleBasic
			);
			this.textTypingContentsDone[i].addColor(textDoneColor[0], 0);
			this.textTypingContentsDone[i].anchor.set(0.5);

			this.helmetDone[i] = new Helmet();
			this.helmetDone[i].move(
				game.world.centerX - 200 - i * OFFSET_WORD_X - 50,
				TYPING_CONTENT_Y - 110
			);
			this.helmetDone[i].setType(Hammer.TYPE_PPYONG);
			this.helmetDone[i].alpha(0);
		}

		var textPreviewColor = [ '#666666', '#888888', '#777777' ];
		this.textTypingContentPreview = [];
		for(var i = 0; i < WhacAMole.TYPING_CONTENT_PREVIEW_COUNT; i++) {
			this.textTypingContentPreview[i] = game.add.text(
				game.world.centerX + 200 + i * OFFSET_WORD_X,
				TYPING_CONTENT_Y, "", textStyleBasic
			);
			this.textTypingContentPreview[i].addColor(textPreviewColor[0], 0);
			this.textTypingContentPreview[i].anchor.set(0.5);
		}

		// keyboard
		this.keyMapper = new KeyMapper();
		this.keyboard = null;
		if(sessionStorageManager.getPlayingAppName().indexOf("korean") > 0)
			this.keyboard = new Keyboard(this.keyMapper, Keyboard.KOREAN, Keyboard.WHAC_A_MOLE_OFFSET_POS_Y);
		else
			this.keyboard = new Keyboard(this.keyMapper, Keyboard.ENGLISH, Keyboard.WHAC_A_MOLE_OFFSET_POS_Y);
		this.keyboard.addCallback(
			Phaser.KeyCode.ESC,	// keyCode
			null,	// keyDownHandler
			(function() { this.back(); }).bind(this),	// keyUpHandler
			"whac a mole"	// callerClassName
		);

		game.input.keyboard.processKeyPress = (function(event) {
			if(self.isOnStage === false)
				return;

			self.checkTypingContents(event);
		});
		this.shiftKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);


		this.keyboardMole = new KeyboardMole(this.keyboard);

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


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


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

	startGame: function() {
		this.isOnStage = true;
		this.stageTimer.start();

		this.showTypingContents();
		this.showHighlightKey();
	},

	timeOver: function() {
		this.isOnStage = false;

		for(var i = 0; i < WhacAMole.TYPING_CONTENT_DONE_COUNT; i++) {
			this.textTypingContentsDone[i].text = "";
			this.helmetDone[i].alpha(0);
		}

		this.textTypingBracket.text = "";

		this.textTypingContent.clearColors();
		this.textTypingContent.addColor(WhacAMole.COLOR_CONTENT_RIGHT, 0);
		this.textTypingContent.text = "= 연습 끝 =";

		for(var i = 0; i < WhacAMole.TYPING_CONTENT_PREVIEW_COUNT; i++) {
			this.textTypingContentPreview[i].text = "";
		}

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

	initTypingData: function() {
		this.typingRandomLetters = this.loadLetters();
		// console.log(this.typingRandomLetters);
		this.typingRandomLettersLength = this.typingRandomLetters.length;
		this.typingIndex = 0;
	},


	shuffleLettetFollowingFKey: function(wordList) {
		var shuffleLetters = TypingTextManager.shuffledArray(wordList);

		var letters = [];
		for(var i = 0; i < shuffleLetters.length; i++) {
			if(isKoreanTypingApp())
				letters.push("ㄹ");
			else
				letters.push("f");

			letters.push(shuffleLetters[i]);
		}

		return letters;
	},

	shuffleLettetFollowingJKey: function(wordList) {
		var shuffleLetters = TypingTextManager.shuffledArray(wordList);

		var letters = [];
		for(var i = 0; i < shuffleLetters.length; i++) {
			letters.push(shuffleLetters[i]);

			if(isKoreanTypingApp())
				letters.push("ㅓ");
			else
				letters.push("j");
		}

		return letters;
	},

	isLeftHandLetter: function(letter) {
		switch(letter) {
			case "t":
			case "g":
			case "b":
			case "ㅅ":
			case "ㅎ":
			case "ㅠ":
			return true;
		}

		return false;
	},

	shuffleLettetFollowingFJKey: function(wordList) {
		var shuffleLetters = TypingTextManager.shuffledArray(wordList);

		var letters = [];
		for(var i = 0; i < shuffleLetters.length; i++) {
			if(this.isLeftHandLetter(shuffleLetters[i])) {
				letters.push(shuffleLetters[i]);

				if(isKoreanTypingApp())
					letters.push("ㅓ");
				else
					letters.push("j");
			} else {	// right hand letter
				if(isKoreanTypingApp())
					letters.push("ㄹ");
				else
					letters.push("f");

				letters.push(shuffleLetters[i]);
			}
		}

		return letters;
	},

	suffleAllLetters: function() {
		var allLetters = [];
		if(isKoreanTypingApp()) {
			allLetters = koreanBasicLeftWordList;
			allLetters = allLetters.concat(koreanBasicRightWordList);
			allLetters = allLetters.concat(koreanBasicRightWordList);
			allLetters = allLetters.concat(koreanLeftUpperWordList);
			allLetters = allLetters.concat(koreanRightUpperWordList);
			allLetters = allLetters.concat(koreanLeftLowerWordList);
			allLetters = allLetters.concat(["ㅡ"]);	// koreanRightLowerWordList);
			allLetters = allLetters.concat(koreanSecondFingerWordList);
		} else {
			allLetters = englishBasicLeftWordList;
			allLetters = allLetters.concat(englishBasicRightWordList);
			allLetters = allLetters.concat(englishBasicRightWordList);
			allLetters = allLetters.concat(englishLeftUpperWordList);
			allLetters = allLetters.concat(englishRightUpperWordList);
			allLetters = allLetters.concat(englishLeftLowerWordList);
			allLetters = allLetters.concat(["m"]);	// englishRightLowerWordList);
			allLetters = allLetters.concat(englishSecondFingerWordList);
		}

		return TypingTextManager.shuffledArray(allLetters);
	},

	loadLetters: function() {
		var appName = "";
		var letters = [];

		if(isKoreanTypingApp()) {
			letters = letters.concat(["ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ"]);
			letters = letters.concat(this.shuffleLettetFollowingJKey(koreanBasicLeftWordList));
			letters = letters.concat(this.shuffleLettetFollowingFKey(koreanBasicRightWordList));

			letters = letters.concat(["ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ"]);
			letters = letters.concat(this.shuffleLettetFollowingJKey(koreanLeftUpperWordList));
			letters = letters.concat(this.shuffleLettetFollowingFKey(koreanRightUpperWordList));
			letters = letters.concat(this.shuffleLettetFollowingJKey(koreanLeftLowerWordList));

			letters = letters.concat(["ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ"]);
			// letters = letters.concat(this.shuffleLettetFollowingFKey(koreanRightLowerWordList));
			letters = letters.concat(this.shuffleLettetFollowingFJKey(koreanSecondFingerWordList.concat("ㅡ")));

			// letters = letters.concat(this.shuffleLettetFollowingJKey(koreanLeftUpperDoubleWordList));
			// letters = letters.concat(this.shuffleLettetFollowingFKey(koreanRightUpperDoubleWordList));

			for(var i = 0; i < 5; i++) {
				letters = letters.concat(["ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ", "ㄹ", "ㅓ"]);
				letters = letters.concat(this.suffleAllLetters());
			}
		}
		else {	// isEnglishTypingApp
			letters = letters.concat(["f", "j", "f", "j", "f", "j"]);
			letters = letters.concat(this.shuffleLettetFollowingJKey(englishBasicLeftWordList));
			letters = letters.concat(this.shuffleLettetFollowingFKey(englishBasicRightWordList));

			letters = letters.concat(["f", "j", "f", "j", "f", "j"]);
			letters = letters.concat(this.shuffleLettetFollowingJKey(englishLeftUpperWordList));
			letters = letters.concat(this.shuffleLettetFollowingFKey(englishRightUpperWordList));
			letters = letters.concat(this.shuffleLettetFollowingJKey(englishLeftLowerWordList));

			letters = letters.concat(["f", "j", "f", "j", "f", "j"]);
			// letters = letters.concat(this.shuffleLettetFollowingFKey(englishRightLowerWordList));
			letters = letters.concat(this.shuffleLettetFollowingFJKey(englishSecondFingerWordList.concat("m")));

			// letters = letters.concat(this.shuffleLettetFollowingJKey(englishLeftUpperDoubleWordList));
			// letters = letters.concat(this.shuffleLettetFollowingFKey(englishRightUpperDoubleWordList));

			for(var i = 0; i < 5; i++) {
				letters = letters.concat(["f", "j", "f", "j", "f", "j", "f", "j", "f", "j"]);
				letters = letters.concat(this.suffleAllLetters());
			}
		}
		// console.log(letters);

		return letters;
	},

	showTypingContents: function() {
		for(var i = 0; i < WhacAMole.TYPING_CONTENT_DONE_COUNT; i++) {
			var doneIndex = this.typingIndex - i - 1;
			if(doneIndex < 0) {
				this.textTypingContentsDone[i].text = "";
				this.helmetDone[i].alpha(0);
			} else {
				this.textTypingContentsDone[i].text = this.typingRandomLetters[doneIndex];
				// this.helmetDone[i].change(Helmet.TYPE_PPYONG);
				this.helmetDone[i].alpha(1);

				if(i == 0) {
					this.helmetDone[i].dropDownTween(10);
				}
			}
		}

		if(this.typingIndex == this.typingRandomLettersLength) {
			this.textTypingContent.text = "";
			return;
		}

		var nextLetter = this.typingRandomLetters[this.typingIndex];
		this.textTypingContent.text = nextLetter;
		// var keyID = this.keyboard.keyMapper.getKeyIDOfText(this.typingRandomLetters[this.typingIndex]);

		var keyID = this.keyMapper.getKeyIDOfText(nextLetter);
		// console.log(keyID);
		this.bigMole.changeColor(keyID);
		this.bigMole.changeHelmetColor(this.hammer.getType());
		this.bigMole.showUp();

		this.keyboardMole.changeColor(keyID);
		this.keyboardMole.show();
		this.keyboardMole.moveToKey(nextLetter);


		for(var i = 0; i < WhacAMole.TYPING_CONTENT_PREVIEW_COUNT; i++) {
			var previewIndex = this.typingIndex + i + 1;
			if(previewIndex < this.typingRandomLetters.length)
				this.textTypingContentPreview[i].text = this.typingRandomLetters[previewIndex];
			else
				this.textTypingContentPreview[i].text = "";
		}
	},

	hideHighlightKey: function() {
		var prevText = this.typingRandomLetters[this.typingIndex];
		if(prevText === undefined)
			return;

		this.keyboard.hideHighlight(prevText);
	},

	showHighlightKey: function() {
		var typingText = this.typingRandomLetters[this.typingIndex];
		if(typingText === undefined)
			return;

		// this.keyboard.showHighlight(typingText, this.leftHand, this.rightHand);
	},

	getKeyCode: function(text) {
		return this.keyMapper.getKeyIDOfText(text);
	},

	isKeyPressed: function(inputContent, typingContent) {
		var inputContentKeyCode = this.getKeyCode(inputContent);
		var typingContentKeyCode = this.getKeyCode(typingContent);

		if(inputContentKeyCode !== typingContentKeyCode)
			return false;

		var isShiftInputContent = this.shiftKey.isDown;
		var isShiftTypingContent = this.keyMapper.isShiftText(typingContent);

		if(isShiftInputContent !== isShiftTypingContent)
			return false;

		return true;
	},

	checkTypingContents: function(event) {
		var inputContent = event.key;
		if(inputContent == undefined)
			inputContent = String.fromCharCode(event.charCode);
    	var typingContent = this.typingRandomLetters[this.typingIndex];

		if(this.isKeyPressed(inputContent, typingContent)) {
			var plusScore = this.hammer.getScore();
			this.scoreManager.plusScore(plusScore);

			this.playNextContent();

			for(var i = 0; i < WhacAMole.TYPING_CONTENT_DONE_COUNT - 1; i++) {
				var index = WhacAMole.TYPING_CONTENT_DONE_COUNT - 1 - i;
				var prevHelmetType = this.helmetDone[index - 1].getType();
				this.helmetDone[index].change(prevHelmetType);
			}
			this.helmetDone[0].change(this.hammer.getType());
			this.hammer.smash();
			this.bigMole.changeHelmetColor(this.hammer.getType());	// this should call after hammer smash

			if(this.typingIndex === this.typingRandomLettersLength) {
				// this.goResult();
			}
		} else {
			this.hammer.changeType(Hammer.TYPE_PPYONG);
			this.bigMole.changeHelmetColor(this.hammer.getType());
		}
	},

	playNextContent: function() {
		this.hideHighlightKey();

		this.typingIndex++;
		this.showTypingContents();
		this.showHighlightKey();
	}
}


WhacAMole.TYPING_CONTENT_PREVIEW_COUNT	= 3;
WhacAMole.TYPING_CONTENT_DONE_COUNT		= 3;
// WhacAMole.TYPING_COUNT_PLUS_ENTER		= 1;

// WhacAMole.OFFSET_RIGHT_ALIGN			= 10;

WhacAMole.STAGE_TIMER_SEC				= 60;

WhacAMole.COLOR_CONTENT_INPUT			= "#dddddd";
WhacAMole.COLOR_BRACKET					= "#dddd70";
WhacAMole.COLOR_CONTENT_RIGHT			= "#ffff4d";