var TypingTest = {

	create: function() {
		var self = this;

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

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

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

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

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


		this.averageTypingSpeedText = new AverageTypingSpeed();
		this.contentProgressText = new ContentProgress();


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

		var TYPING_CONTENT_Y = 320;

		if( (isKoreanTypingApp() && isTypingSentenceApp())
			|| (isEnglishTypingApp() && isTypingSentenceApp()) )
			textStyleBasic.font = "bold 48px Arial";
		else
			textStyleBasic.font = "bold 84px Arial";

		this.textTypingContent = game.add.text(
			game.world.centerX, TYPING_CONTENT_Y,
			"", textStyleBasic
		)
			.setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2)
			.addColor(TypingTest.COLOR_CONTENT_INPUT, 0);
		this.textTypingContent.anchor.set(0.5);

		var TYPING_OFFSET_Y = 90;
		textStyleBasic.font = "32px Arial";

		var textDoneColor = [ '#99994d', '#77774d', '#66664d' ];
		this.textTypingContentsDone = [];
		this.textTypingRecordsDone = [];
		for(var i = 0; i < TypingTest.TYPING_CONTENT_DONE_COUNT; i++) {
			this.textTypingContentsDone[i] = game.add.text(
				game.world.centerX, TYPING_CONTENT_Y + TYPING_OFFSET_Y + i * 50,
				"", textStyleBasic
			)
				// .setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2)
				.addColor(textDoneColor[i], 0);
			this.textTypingContentsDone[i].anchor.set(0.5);

			var SCORE_POSITION_X = 900;
			if(isTypingWordApp())
				SCORE_POSITION_X = 700;

			this.textTypingRecordsDone[i] = game.add.text(
				SCORE_POSITION_X, TYPING_CONTENT_Y + TYPING_OFFSET_Y + i * 50,
				"", textStyleBasic
			)
				// .setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2)
				.addColor(textDoneColor[i], 0);
			this.textTypingRecordsDone[i].anchor.set(0.5);
		}

		var textPreviewColor = [ '#999999', '#888888', '#777777' ];
		this.textTypingContentPreview = [];
		for(var i = 0; i < TypingTest.TYPING_CONTENT_PREVIEW_COUNT; i++) {
			this.textTypingContentPreview[i] = game.add.text(
				game.world.centerX, TYPING_CONTENT_Y - TYPING_OFFSET_Y - i * 50,
				"", textStyleBasic
			)
				// .setShadow(3, 3, 'rgba(0, 0, 0, 0.5)', 2)
				.addColor(textPreviewColor[i], 0);
			this.textTypingContentPreview[i].anchor.set(0.5);
		}


		// input text
		this.inputTextContent = new InputTypeText(game.world.centerX, TYPING_CONTENT_Y + 260);
		this.inputTextContent.anchor.set(0.5);
		this.inputTextContent.canvasInput.value('');
		this.inputTextContent.canvasInput.focus();
		this.inputTextContent.canvasInput.placeHolder("입력 후 [ Enter ]키를 누르세요");
		// inputTextContent.canvasInput._onkeydown = this.checkInputText;
		// inputTextContent.canvasInput._onkeyup = function() {
		this.inputTextContent.canvasInput._onkeyup = function() {
			self.checkTypingContents(event);
		}


		this.animalList = new AnimalList(GAME_SCREEN_SIZE.y - 110);


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


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

	/*
	countDown() {
		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() {
		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 }, GAME_SCREEN_SIZE.x, Phaser.Easing.Linear.None, true);
		countDownTween.onComplete.add(this.tweenCountDown, this);

		this.countDownNumber--;
	}
	*/


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

	startGame: function() {
		this.averageTypingSpeedText.print(0);

		this.showTypingTestContents();
		this.showPlayingWordNumber();
	},

	gameOver: function() {
		var gameOverText = new GameOverText();

		this.animalList.stopAnimation();

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

	goResult: function() {
		sessionStorageManager.setRecord(this.typingRecordTotal);

		location.href = '../../web/client/result.html';
	},

	initTypingData: function() {
		var typingTextMan = new TypingTextManager();

		var typingPracticeContents = this.getTypingTestContents();
		// console.log(typingPracticeContents);
		typingTextMan.makeTestContents(typingPracticeContents);
		var wordCountForStage = TypingTest.WORD_COUNT_FOR_STAGE;
		if(isDebugMode())
			wordCountForStage = 3;
		typingTextMan.slice(0, wordCountForStage);
		this.typingRandomContents = typingTextMan.getContents();
		// console.log(this.typingRandomContents);
		this.typingContentLength = this.typingRandomContents.length;
		this.typingIndex = 0;


		this.isTyping = false;
		this.timeTypingStart = 0;
		this.timeTypingEnd = 0;

		this.typingLetterCountTotal = 0;
		this.typingRecordTotal = 0;
	},


	getTypingTestContents: function() {
		var typingTestContents = this.loadTestContent();
		// console.log('playingStageData.language : ' + playingStageData.language);
		// console.log('playingStageData.level : ' + playingStageData.level);
		// console.log('typingTestContents : ' + typingTestContents);

		this.typingRecordForLines = [];
		this.typingElapsedTime = [];
		for(var i = 0; i < typingTestContents.length; i++) {
			this.typingRecordForLines[i] = 0;
			this.typingElapsedTime[i] = 0;
		}

		return typingTestContents;
	},

	loadTestContent: function() {
		var appName = "";
		if(isTypingTestApp())
			appName = sessionStorageManager.getPlayingAppName().substring(5);
		else if(isTypingPracticeApp())
			appName = sessionStorageManager.getPlayingAppName().substring(9);

		var testContent = [];
		switch(appName) {
			case "korean_basic":
			testContent = koreanBasicWordList;
			break;
			case "korean_left_upper":
			testContent = koreanLeftUpperWordList;
			break;
			case "korean_second_finger":
			testContent = koreanSecondFingerWordList;
			break;
			case "korean_right_upper":
			testContent = koreanRightUpperWordList;
			break;
			case "korean_left_lower":
			testContent = koreanLeftLowerWordList;
			break;
			case "korean_right_lower":
			testContent = koreanRightLowerWordList;
			break;
			case "korean_left_upper_double":
			testContent = koreanLeftUpperDoubleWordList;
			break;
			case "korean_right_upper_double":
			testContent = koreanRightUpperDoubleWordList;
			break;
			case "korean_word":
			testContent = koreanWordList;
			break;
			case "korean_sentence":
			testContent = koreanSentenceList;
			break;

			case "english_basic":
			testContent = englishBasicWordList;
			break;
			case "english_left_upper":
			testContent = englishLeftUpperWordList;
			break;
			case "english_second_finger":
			testContent = englishSecondFingerWordList;
			break;
			case "english_right_upper":
			testContent = englishRightUpperWordList;
			break;
			case "english_left_lower":
			testContent = englishLeftLowerWordList;
			break;
			case "english_right_lower":
			testContent = englishRightLowerWordList;
			break;
			case "english_word":
			testContent = englishWordList;
			break;
			case "english_sentence":
			testContent = englishSentenceList;
			break;
		}

		return testContent;
	},

	showTypingTestContents: function() {
		for(var i = 0; i < TypingTest.TYPING_CONTENT_DONE_COUNT; i++) {
			var doneIndex = this.typingIndex - i - 1;
			if(doneIndex < 0) {
				this.textTypingContentsDone[i].text = "";
				this.textTypingRecordsDone[i].text = "";
			} else {
				this.textTypingContentsDone[i].text = this.typingRandomContents[doneIndex];
				this.textTypingRecordsDone[i].text = Math.floor(this.typingRecordForLines[doneIndex]);
			}
		}

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

		this.textTypingContent.text = this.typingRandomContents[this.typingIndex];

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

	resetTypingContent: function() {
		this.textTypingContent.clearColors();
		this.textTypingContent.addColor(TypingTest.COLOR_CONTENT_INPUT, 0);
		this.inputTextContent.canvasInput.value('');
	},

	checkTypingContents: function(event) {
		if(event.keyCode == Phaser.Keyboard.ENTER) {
			// console.log("### enter ###");
			var inputContent = this.inputTextContent.canvasInput.value();
			var typingContent = this.typingRandomContents[this.typingIndex];

			if(inputContent === typingContent) {
				this.calculateTypingRecord(typingContent);
				this.playNextContent();

				if(this.typingIndex == this.typingContentLength)
					this.goResult();
					// this.state.start('TypingTestResult');
			}
		}
		else {
			// console.log(this.inputTextContent.canvasInput.value());
			if(this.isTyping == false) {
				// console.log(event);
				this.setTimeTypingStart();
			}

			this.showTypingContentHighlight();
		}
	},

	showTypingContentHighlight: function() {
		var typingContent = this.typingRandomContents[this.typingIndex];
		var inputContent = this.inputTextContent.canvasInput.value();

		this.textTypingContent.clearColors();
		this.textTypingContent.addColor(TypingTest.COLOR_CONTENT_RIGHT, 0);

		if(typingContent == null)
			return;

		var typingContentLength = typingContent.length;
		for(var i = 0; i < typingContentLength; i++) {
			// console.log("typingContent.charAt(i) : " + typingContent.charAt(i));
			// console.log("inputContent.charAt(i) : " + inputContent.charAt(i));

			if(typingContent.charAt(i) != inputContent.charAt(i)) {
				this.textTypingContent.addColor(TypingTest.COLOR_CONTENT_INPUT, i);
				return;
			}
		}
	},

	calculateTypingRecord: function(typingContent) {
		// console.log('입력 단어 : ' + this.typingRandomContents[this.typingIndex]);

		this.isTyping = false;
		this.timeTypingEnd = game.time.elapsedSince(0);
		// console.log('this.timeTypingEnd : ' + this.timeTypingEnd);

		var elapsedTimeMS = this.timeTypingEnd - this.timeTypingStart;
		// console.log('elapsedTimeMS : ' + elapsedTimeMS);

		var typingContentLength = StringUtil.getUnicodeAlphabetCount(typingContent);
		// console.log('typingContentLength : ' + typingContentLength);
		var typingContentPlusEnterCount = typingContentLength + TypingTest.TYPING_COUNT_PLUS_ENTER;

		var typingRecord = (typingContentPlusEnterCount + TypingTest.TYPING_COUNT_PLUS_ENTER) * 60000 / elapsedTimeMS;

		this.typingElapsedTime[this.typingIndex] = elapsedTimeMS;
		this.typingLetterCountTotal += typingContentPlusEnterCount;
		this.typingRecordForLines[this.typingIndex] = typingRecord;
		// console.log(this.typingRecordForLines[this.typingIndex]);

		var typingElapsedTimeTotal = 0;
		for(var i = 0; i <= this.typingIndex; i++) {
			// console.log('i : ' + i + ' - time : ' + this.typingElapsedTime[i]);
			typingElapsedTimeTotal += this.typingElapsedTime[i];
		}
		this.typingRecordTotal = this.typingLetterCountTotal * 60000 / typingElapsedTimeTotal;
		// console.log(this.typingLetterCountTotal);
		// console.log(typingElapsedTimeTotal);
		// console.log(typingRecordTotal);

		var typingRecordTotalInteger = Math.floor(this.typingRecordTotal);
		this.averageTypingSpeedText.print(typingRecordTotalInteger);
		// console.log('-------------- total --------------');
		// console.log('typingLetterCountTotal : ' + this.typingLetterCountTotal);
		// console.log('typingElapsedTimeTotal : ' + typingElapsedTimeTotal);
		// console.log('typingRecordTotal : ' + typingRecordTotal);
		// console.log('-----------------------------------');

		var animalLevelID = Animal.animalLevelIDByRecord(typingRecordTotalInteger, Animal.TYPE_TEST);
		this.animalList.activate(animalLevelID);
		this.animalList.tweenAnimation(Animal.ANIMATION_TYPE_CHANGE);
	},

	playNextContent: function() {
		this.typingIndex++;
		this.showTypingTestContents();
		this.showPlayingWordNumber();
		this.resetTypingContent();
	},

	showPlayingWordNumber: function() {
		this.contentProgressText.print(this.typingIndex + 1, this.typingContentLength);
	},

	setTimeTypingStart: function() {
		this.timeTypingStart = game.time.elapsedSince(0);
		var timeGap = this.timeTypingStart - this.timeTypingEnd;

		if(timeGap < 50)
			return;

		this.isTyping = true;
		// console.log('last End : ' + this.timeTypingEnd);
		// console.log('this.timeTypingStart : ' + this.timeTypingStart);

		// console.log('time gap : ' + (this.timeTypingStart - this.timeTypingEnd));
	}

}


TypingTest.TYPING_CONTENT_PREVIEW_COUNT	= 3;
TypingTest.TYPING_CONTENT_DONE_COUNT	= 3;
TypingTest.TYPING_COUNT_PLUS_ENTER		= 1;

TypingTest.OFFSET_RIGHT_ALIGN			= 10;

TypingTest.WORD_COUNT_FOR_STAGE			= 10;

TypingTest.COLOR_CONTENT_INPUT			= "#dddddd";
TypingTest.COLOR_CONTENT_RIGHT			= "#ffff4d";