'use strict';

/**
@author Felipe Vargas RIC-SOUTH
A module representing the  GAME RETO/CHALLENGE the idea is anwser some question and advance in some levels 
@Module sgGameChallenge 
**/
define(['jquery','sgSound','jquery.countdown','sgPopUp'], function($, sgSound, jqCount, sgPopUp) {

	var app = {};
	var currentGame;



	function changeLevel() {

		var level = currentGame.data('level');
		var levels = currentGame.find("[data-sg-id='game-item-level']");
		var levelDiv = levels.eq(level);
		var questions = levelDiv.find("[data-sg-id='game-item-question']");

		var pos = Math.floor(Math.random() * questions.length);
		
		var board = currentGame.find('.board-quest');

		board.find('[data-sg-id="game-item-question"]').remove();
		board.append(questions[pos]);
		changeDisplayArrow('none');

		if ((level+1)==currentGame.data('totalLevels')){
			board.find('.arrow-next').remove();
			
		}

		currentGame.data('level',level+1);

		/*si desea que el cronometro no se reinicie cada vez que cambia de pregunta si no que continue el tiempo
		haga la variable callResume igual a true, por ejemplo game.data('callResume',true); donde game es [data-sg-id='game-challenge']*/
		if(currentGame.data('callResume')){
			resumeChron();
		}else{
			startChron();
		}
	}

	function startGame() {

		currentGame = $(this).data('currentGame');
		var board = currentGame.find('.board-quest');
		var helps= $('<div>').addClass('helps');
		var helpHalf=$('<div>').attr('data-sg-key','1').addClass('half-help').bind("click", clickHelps);
		var helpPublic=$('<div>').attr('data-sg-key','2').addClass('public-help').bind("click",clickHelps);

		helps.append(helpHalf).append(helpPublic);
		board.append(helps);

		changeLevel();
		$(this).parent().find('[data-sg-id=btn-popup-close]').click();

	}

	function optionClick() {
		var $this = $(this);

		$this.addClass('select-option standby');
		$this.unbind();

		pauseChron();

		var interval= setInterval(function(){ 
			$this.removeClass('select-option standby');
			$this.addClass('error-option');
			triggerFeedback($this);
			clearInterval(interval);
			onClicksOptions($this.parent());
			sg.sound("error");
			resumeChron();
		}, 4000);

		offClicksOptions($this.parent());
	}

	function anwserClick() {

		var $this = $(this);

		$this.addClass('select-option standby');

		pauseChron();

		var interval= setInterval(function(){ 
			$this.removeClass('select-option standby');
			$this.addClass('correct-option');
			changeDisplayArrow('block');
			clearInterval(interval);
			sg.sound("success");
//			sg.sound('../../common/sounds/success.ogg');
			
			// SI HAY RETROALIMENTACION POR RESPUESTA CORRECTA
			var question= $this.parent().parent();
			var popupCorrect = question.find('>[data-sg-id="btn-popup"][data-sg-key="correct"]');
			if (popupCorrect )
				popupCorrect.click();

			var win_final = question.parent().parent().attr("data-sg-win");

			if ( currentGame.data('level') == currentGame.data('totalLevels') && (!win_final) ){ 
				sg.sound("claps");
				setTimeout(function(){
					$('div[data-sg-id="btn-popup"][data-sg-key="won"]').click();
				}, 1000);
			}
			
		}, 4000);

		removeClickOptions($this.parent());
	}

	function changeDisplayArrow(display){

		var board=currentGame.find('.board-quest');
		var arrowNext= board.find('.arrow-next');
		arrowNext.css('display',display);

	}

	function removeClickOptions(question){
		
		var options = question.find("[data-sg-id='game-item-option']");
		var anwser = question.find("[data-sg-id='game-item-anwser']");
		options.unbind();
		anwser.unbind();
	}
	function offClicksOptions(question){

		var options = question.find("[data-sg-id='game-item-option']");
		var anwser = question.find("[data-sg-id='game-item-anwser']");
		options.attr('disabled', true);
		anwser.attr('disabled', true);
		
	}

	function onClicksOptions(question){

		var options = question.find("[data-sg-id='game-item-option']");
		var anwser = question.find("[data-sg-id='game-item-anwser']");
		options.removeAttr('disabled');
		anwser.removeAttr('disabled');	
	}

	function triggerFeedback(option){

		var question= option.parent();
		question.find('>[data-sg-id="btn-popup"]').click();
	}

	function clickHelps(e){
		var $me=$(this);
		var key= $(this).attr('data-sg-key');

		switch (key){
			case "1":{

				var board=currentGame.find('.board-quest');

				var options=board.find("[data-sg-id='game-item-option']");
				var pos = Math.floor(Math.random() * options.length);
				options.eq(pos).css("visibility", "hidden");

				var options=board.find("[data-sg-id='game-item-option']");
				var pos2 = Math.floor(Math.random() * options.length);

				while (pos2 == pos)
					pos2 = Math.floor(Math.random() * options.length);

				options.eq(pos2).css("visibility", "hidden");
				

				$me.unbind();
				$me.addClass('disabled');

				break; 
			}
			case "2":{

				$me.unbind();
				$me.addClass('disabled');

				var closeBtn= $('<div data-sg-id="btn-popup-close" class="icon_close_button" ></div>');

				var divPopUp= $('<div data-sg-id="item-popup">')
				.append(closeBtn).append('<p>Pregúntale a tus compañeros</p>')
				.addClass('popup-ask-public');
				sgPopUp.popupOpen(divPopUp);

				pauseChron();

				closeBtn.click(function(){
					resumeChron();
				});

				break; 
			}
		}

	}

	function startChron(){
		var chronometer= currentGame.find('#chronometer');
		chronometer.countdown360().start();
	}

	function stopChron(){
		var chronometer= currentGame.find('#chronometer');
		chronometer.countdown360().stop();
	}

	function pauseChron(){
		var chronometer= currentGame.find('#chronometer');
		chronometer.countdown360().pause();
	}

	function resumeChron(){
		var chronometer= currentGame.find('#chronometer');
		chronometer.countdown360().resume();
	}




	app.init = function() {

		var games = $("[data-sg-id='game-challenge']");
		sg.sound("success",false);
		sg.sound("claps",false);
		games.each(function(index, value) {

			var game = $(value);

			var arrowNext= $('<div>').addClass('arrow-next').css('display','none');
			var boardQuest=$("<div>").addClass('board-quest');
			arrowNext.click(changeLevel);
			boardQuest.append(arrowNext);

			var chronometer= $('<div>').attr('id','chronometer');

			chronometer.countdown360({
       	 		radius      : 60,
         		seconds     : 30,
         		fontColor   : '#FFFFFF',
         		strokeStyle : '#E95720',
         		fillStyle:'#EE7B1D',
         		autostart   : false,
         		onComplete  : function () { console.log('done') }
		   	});

			game.append(chronometer);			
			game.append(boardQuest);
			game.data('level', 0);

			var levels = game.find("[data-sg-id='game-item-level']");
			if (levels.length == 0) {
				console.error('The game needs at least a level');
				return;
			}

			game.data('totalLevels', levels.length);

			levels.css('display', 'none');

			levels.each(function(index, value) {

				var level = $(this);
				var questions = level.find("[data-sg-id='game-item-question']");

				if (questions.length == 0) {
					console.error('The level:' + index + ' needs at least a question');
					return;
				}

				questions.each(function(index, value)
					{
						var question = $(this);
						var questText = question.find("[data-sg-id='game-item-quest']");
						var options = question.find("[data-sg-id='game-item-option']");
						var anwser = question.find("[data-sg-id='game-item-anwser']");

						if (questText.length == 0) {
							console.error('The question :' + index + ' does not have text ');
							return;
						}
						// if (options.length != 3) {
						// 	console.error('The game only allow three options for each question ');
						// 	return;
						// }
						if (anwser.length == 0) {
							console.error('The question needs some anwser');
							return;
						}
						options.click(optionClick);
						anwser.click(anwserClick);
					}
				);

			});



			var popupBtnInit = game.find(" > [data-sg-id='btn-popup']");


			var key = popupBtnInit.attr('data-sg-key');

			var popupItemInit = $("[data-sg-id=item-popup][data-sg-key=" + key + "]");


			var btnStartGame = popupItemInit.find('[data-sg-id=btn-init]');
			btnStartGame.data('currentGame', game);
			btnStartGame.click(startGame);

			var initnow = popupBtnInit.attr("data-sg-initgame");
			if(!initnow){
				popupBtnInit.click();
			}




		});



	}



	return app;
});