/**
 * this controller reponsable for voting poll and view result after voting 
 */
mainVote.controller("pollController",function($scope, $http, $cookies,$location,$filter) {
  
    var myspHelper = ns_Z7_69900BS0M06T40ADHDAQIA00T2_spHelper;
	var vm=this;
	vm.userVote='';
  var translateFilter = $filter('translate');	
	//hide poll form untill get publish poll loading
  vm.IsHidden = true;
	
  vm.showLang = false;
  vm.hideLoading = false;
  vm.hidePoll=true;
  vm.hidePollResult=true;
  myspHelper.renderingLocale.substring(0, 2) == "en"?  vm.showLang = true : vm.showLang = false;

  vm.errorText='';
     var handleRender = function(){
	 $("#chartdivPollHome").css("height", "223px");
 }
URL='/Poll/pollController/polls?status=0';
//get current publish poll
$http.get(URL).success(
function(response) {

			//var jsonObj = response;
			vm.today = new Date();
			vm.poll=response[0];

			//check if current poll id exists in cookies
			if($cookies.get("pollID")==vm.poll.id){
			
				vm.hidePoll = true;
				
				//show result form
				vm.hidePollResult = false;
              var newArray = [];

//for each in all result then set in new object
vm.poll.answers.forEach(function(answer)
	{
      if(vm.showLang)
      		{
              newArray.push({"Poll": answer.desc_en,"Votes":answer.answerCount})
            } else 
      		{
              newArray.push({"Poll": answer.desc_ar,"Votes":answer.answerCount})
            }
    });
              
console.log(newArray);              
              AmCharts.isReady = true;
              //configChart = function() {
var chart = AmCharts.makeChart("chartdivPollHome", {
    "type": "pie",
    "theme": "light",
    "dataProvider": newArray,
    "valueField": "Votes",
    "titleField": "Poll" ,
    "balloon": {
        "fixedPosition": true
    },
    "export": {
        "enabled": true
    },
	"listeners": [{
      "event": "drawn",
      "method": handleRender
      }],
   "labelText": "[[value]] "+translateFilter("VOTES")+" [[percents]]%",
                     
                     
}); 
                AmCharts.handleLoad();
 
			//show form voting
			}else{
			
			vm.hidePoll = false;
			vm.hidePollResult = true;
              
              
                     
			}
			
			
		//in case there are error	
		}).error(function(data, status, header,config) {
					
			vm.hidePoll = true;
			vm.hidePollResult = true;
			
			$location.path("error");
				
		});;

		
///vote user 								
vm.sendData = function() {
	
if(vm.validation()){

	vm.vote={"userName":myspHelper.userId,"poll":{"id":vm.poll.id},"answer":{"answerID":0}};
//	alert('sendData >> >> >> Called'+JSON.stringify(vm.userVote));
	
	 for(var i = 0; i<vm.poll.answers.length; i++){
			 
       //check if the select answer
			 if(vm.poll.answers[i].answerID==vm.userVote){
	//set new value count			
			     vm.poll.answers[i].answerCount=vm.poll.answers[i].answerCount+1;
vm.vote.answer.answerID=vm.poll.answers[i].answerID;

			 }
			 
          }
		  
		  
		 
		var data = vm.vote;
		var config = {
		headers : {'Content-Type' : 'application/json'
		}
	}

     //send new vote 
	$http.post('/Poll/pollController/vote',data, config).success(
					
			function(data, status, headers,config) {
				
			vm.poll = data;
			
               var newArray = [];

//for each in all result then set in new object
vm.poll.answers.forEach(function(answer)
	{
      if(vm.showLang)
      		{
              newArray.push({"Poll": answer.desc_en,"Votes":answer.answerCount})
            } else 
      		{
              newArray.push({"Poll": answer.desc_ar,"Votes":answer.answerCount})
            }
    });

              
              AmCharts.isReady = true;
var chart = AmCharts.makeChart("chartdivPollHome", {
    "type": "pie",
    "theme": "light",
    "dataProvider": newArray,
    "valueField": "Votes",
    "titleField": "Poll",
    "balloon": {
        "fixedPosition": true
    },
    "export": {
        "enabled": true
    },"listeners": [{
      "event": "drawn",
      "method": handleRender
      }],
   "labelText": "[[value]] "+translateFilter("VOTES")+" [[percents]]%",
                     
                     
});      
              
                AmCharts.handleLoad();
						//after submit hide the question
						vm.hidePoll = true;
						
						
						//display result
						vm.hidePollResult = false;

						
						
// Find tomorrow's date.
  var expireDate = new Date();
  expireDate.setDate(expireDate.getDate() + 1000);
						
						//set cookies poll id 
						$cookies.put("pollID", vm.poll.id,{'path': '/',
'expires': expireDate,'secure':true});
						
						
					}).error(function(data, status, header,config) {
					
					//after submit hide the question
						vm.hidePoll = true;
						
						//display result
						vm.hidePollResult = false;
						vm.ResponseDetails = "Data: "+ data+ "<hr />status: "+ status+ "<hr />headers: "+ header+ "<hr />config: "+ config;
						var myEl = angular.element( document.querySelector( '#error' ) );
				      $location.path("error");
						myEl.append('Service Not Available<br/>');
						});
}
	};
  
  vm.validation = function(e) {
    console.log("validation >> >> >> called");
   var validation=true;
    
    var msg = "";
    if(vm.userVote==''||vm.userVote==null) {
        var a=document.documentElement.lang;
       msg=(a=="ar"?"الرجاء اختيار الاجابة":"Please select an answer first");
      validation=false;
	  vm.errorText=msg;
      
    }
    console.log("msg >> >>"+msg);
    
    //get current poll to check if     
  		$.ajax({
              type: 'GET',
              url: URL,
              cache: false,
              async: false,
              processData: false,
              contentType: 'application/json',
              success: function (data, status, jqXHR) {
                  currentPoll = data[0];e
                
                //need check if current vote equals published date
                  if(currentPoll.id!=vm.poll.id){
  				  console.log("NOT EQUALS");
    				validation=false;
   					location.reload();
   
  	            }
              },
              error: function (xhr, ajaxOptions, thrownError) {
				  alert('Service Not Available >>');
                  poll = xhr;
              }
            });
  
    return validation;
}
 
  
});


