/**
* @author: María Andrea Cruz Blandón
* @description:  This plugin allows to declare a hangman game. It is possible to have more than one game in the html page.
* @module: sgGameHangman
**/

define(['jquery', 'sgSound'], function($, sgSound){
	var app = {};
	app.pathImg = "../../common/img/modules/sgGameHangman/";
	app.stage ="escenario.png";
	app.head ="cabeza.png";
	app.body = "cuerpo.png";
	app.rightArm = "brazoderecho.png";
	app.leftArm = "brazoizquierdo.png";
	app.rightLeg = "piernaderecha.png";
	app.leftLeg = "piernaizquierda.png";
	app.hangman = "ahorcado.png";
	app.winner = "ganador.png";
	app.init = function(){
		var $hangmanGame = $('[data-sg-id=game-hangman]');

		if($hangmanGame.length == 0) return;

		$hangmanGame.each(function(e, i) {
			var $me = $(this);
			//if there is a rand attribute that means all words will appear randomly.
			var $randbool = $me.attr('data-sg-rand') != undefined ? 1 : 0;

			//there is required at least one word to be guessed
			var $words = $me.find('[data-sg-id=word]');
			var $totalWords = $words.length;

			if($totalWords == 0){
				console.error('sg-game-hangman: sg-game-hangman should have sg-word children or at least one.');
				return;
			}

			var $wordsArray =[$totalWords];

			for (var index = 0; index < $totalWords; index++) {
				$wordsArray[index] = undefined;
			}

			if($randbool){
				$words.each(function(indexWord, word){
					var wordText = $(this).html();
					var index = Math.floor(Math.random() * $totalWords);
					while ($wordsArray[index] != undefined) {
						index = Math.floor(Math.random() * $totalWords);
					}
					$wordsArray[index] = wordText.toUpperCase();
				});
			}else{
				$words.each(function(indexWord, word){
					var wordText = $(this).html();
					$wordsArray[indexWord] = wordText.toUpperCase();
				});
			}

			$words.remove();
			$me.data('wordsArray',$wordsArray);
			//console.log($wordsArray);

			//Necessary elements that have to be introduced.
			var divKeyboard = $('<div>').addClass('keyboard');
			var divNextButton = $('<div>').addClass('next_button');
			var divRestartButton = $('<div>').addClass('restart_button');
			var divGuessBox = $('<div>').addClass('guessing_box');
			var divDrawingBox = $('<div>').addClass('drawing_box');

			//Build keyboard
			var alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
			for(var letter=0; letter<alphabet.length; letter++){
				var divLetter = $('<div>').addClass('letter').attr('data-sg-key',alphabet[letter]).html(alphabet[letter]);
				divLetter.css('cursor','pointer');
				divLetter.click(pressKey);
				divKeyboard.append(divLetter)
			}    
			// divKeyboard.children().each(function(l,k){
			// 	console.log($(this));
			// })
			//Built next button
			divNextButton.css('cursor','default');
			divNextButton.click(nextWord);
			divNextButton.unbind('click').addClass('disabled');

			//Built restart button
			divRestartButton.css('cursor', 'pointer');
			divRestartButton.click(restartGame);

			//Built guess box
			var divWord = $('<div>').addClass('word');
			divGuessBox.append(divWord);

			//Built divDrawingBox.
			//imgs
			var stageImg = '<img class="stage" src="'+app.pathImg+app.stage+'">';
			divDrawingBox.append(stageImg);

			//Add all elements
			$me.append(divKeyboard);
			$me.append(divNextButton);
			$me.append(divRestartButton);
			$me.append(divGuessBox);
			$me.append(divDrawingBox);

			$me.data('activeWord',0);
			loadWord($me);
		});
	}

	app.updateStage = function(pathImg,stage,game){
		var $me = game;
		var newSrc =  pathImg+stage;
		$me.find('.drawing_box').find('.stage').attr('src',newSrc);
	}

	//Function to show the next word in the game
	function nextWord(){
		var $me = $(this);
		var game = $me.parent();
		game.data('attemps',0)
		loadWord(game);
		//Images
		game.find('.drawing_box > img:gt(0)').remove();

		if(game.data('wordsArray').length == game.data('activeWord')){
			game.find('.keyboard').addClass('disabled').children().removeClass('disabled').css('cursor','default').unbind('click', pressKey);
		}else{
			game.find('.keyboard').removeClass('disabled').children().removeClass('disabled').unbind('click').bind('click', pressKey).css('cursor', 'pointer');
		}
		game.find('.next_button').unbind('click').css('cursor', 'default').addClass('disabled');
	}

	//Function to restar the game
	function restartGame() {
		var $me = $(this);
		var game = $me.parent();
		var $randbool = game.attr('data-sg-rand') != undefined ? 1 : 0;
		var wordsArray = game.data('wordsArray');
		var $totalWords = wordsArray.length;

		var finalWordsArray = [$totalWords];
		for(var i=0; i<$totalWords; i++){
			finalWordsArray[i] = undefined;
		}

		if ($randbool) {
			wordsArray.forEach(function(word){
				var index = Math.floor(Math.random() * $totalWords);
				while(finalWordsArray[index] != undefined){
					index = Math.floor(Math.random() * $totalWords);
				}
				finalWordsArray[index] = word;
			});
			game.data('wordsArray', finalWordsArray);
		}

		game.find('.drawing_box > img:gt(0)').remove();
		game.find('.keyboard').removeClass('disabled').children().removeClass('disabled').unbind('click').bind('click', pressKey).css('cursor', 'pointer');
		game.find('.next_button').unbind('click').css('cursor', 'default').addClass('disabled');

		game.data('activeWord', 0);
		loadWord(game);
	}

	//Fuction to be executed when a letter from alphabet is pressed
	function pressKey(){
		var $me = $(this);
		var character = $me.attr('data-sg-key');

		var game = $me.parent().parent();
		var activeWord = game.data('activeWord');
		var wordsArray = game.data('wordsArray');
		var word = wordsArray[activeWord];
		var fail = word.indexOf(character) >=0? 0:1; 
		var attemps = game.data('attemps');

		$me.unbind('click').addClass('disabled').css('cursor','default');
		if(fail){
			sgSound.sg_sound("error");
			switch(attemps){
				case 0:
					var imgHead = '<img class="head" src="'+app.pathImg+app.head+'">';
					game.find('.drawing_box').append(imgHead);
					break;
				case 1:
					var imgBody = '<img class="body" src="'+app.pathImg+app.body+'">';
					game.find('.drawing_box').append(imgBody);
					break;
				case 2:
					var imgRightArm = '<img class="right_arm" src="'+app.pathImg+app.rightArm+'">';
					game.find('.drawing_box').append(imgRightArm);
					break;
				case 3:
					var imgLeftArm = '<img class="left_arm" src="'+app.pathImg+app.leftArm+'">';
					game.find('.drawing_box').append(imgLeftArm);
					break;
				case 4:
					var imgRightLeg = '<img class="right_leg" src="'+app.pathImg+app.rightLeg+'">';
					game.find('.drawing_box').append(imgRightLeg);
					break;
				case 5:
					var imgLeftLeg = '<img class="left_leg" src="'+app.pathImg+app.leftLeg+'">';
					game.find('.drawing_box').append(imgLeftLeg);
					break;
				case 6:
					var imgHangman = '<img class="hangman" src="'+app.pathImg+app.hangman+'">';
					game.find('.drawing_box > img:gt(0)').remove();
					game.find('.drawing_box').append(imgHangman);
					//Reveal Word
					game.find('.guessing_box').find('.word').children().addClass('wrong');
					var newActiveWord = activeWord + 1;
					game.data('activeWord', newActiveWord);
					app.afterRevealWord(game);
					blockKeyboard(game);
					break;
			}
			game.data('attemps',attemps+1);
		}else{
			sgSound.sg_sound("success");
			var targetKey = '[data-sg-target-key="'+character+'"]'
			game.find('.guessing_box').find('.word').find(targetKey).addClass('guessed');
			var wordLength = word.replace(/\s+/g, '').length;
			var letterGuessed = game.find('.guessing_box').find('.word').find('.letter.guessed').length;

			if(wordLength == letterGuessed){
				var newActiveWord = activeWord + 1;
				game.data('activeWord',newActiveWord);

				//Image
				game.find('.drawing_box > img:gt(0)').remove();
				var imgWinner = '<img class="winner" src="'+app.pathImg+app.winner+'">';
				game.find('.drawing_box').append(imgWinner);

				app.afterRevealWord(game);
				blockKeyboard(game);
			}
		}
	}

	function blockKeyboard(game){
		game.find('.keyboard').addClass('disabled').children().css('cursor','default').unbind('click', pressKey);
		game.find('.next_button').bind('click').css('cursor','pointer').click(nextWord).removeClass('disabled');
	}

	//Function to load the word active. Has to put the gaps in the guess box
	function loadWord(game){
		var activeWord = game.data('activeWord');
		var wordsArray = game.data('wordsArray');

		if(activeWord == wordsArray.length){
			game.find('.guessing_box').find('.word').empty();
			app.finishedGame();
			return;
		}

		var word = wordsArray[activeWord];
		// console.log(word);

		game.data('attemps',0);
		var divWord = game.find('.guessing_box').find('.word');
		divWord.empty();

		for(var i=0; i<word.length; i++){
			var divLetter = $('<div>');
			var character = word[i];
			divLetter.html(character);

			if(character==" "){
				divLetter.addClass('space')
			}else{
				divLetter.addClass('letter');
				character = checkAccents(character);
				divLetter.attr('data-sg-target-key',character);
			}
			divWord.append(divLetter);
		}
	}

	function checkAccents(character){
		switch(character){
			case "Á":
				character="A";
				break;
			case "É":
				character="E";
				break;
			case "Í":
				character="I";
				break;
			case "Ó":
				character="O";
				break;
			case "Ú":
				character="U";
				break;
		}
		return character;
	}

	app.finishedGame = function(){
	}

	//
	app.afterRevealWord = function(){

	}

	return app;
});