/**
 * Created by jaskokoyn on 4/26/2015.
 */
owlChatApp.controller("pollCtrl",["$scope", "$rootScope", "$http", "$timeout", function($scope,$rootScope,$http,$timeout){
    $scope.pid                  =   null;
    $scope.isLoading            =   true;
    $scope.poll                 =   {};
    $scope.alreadyAnswered      =   false;
    $scope.userAnswer           =   null;

    $(document).on("click", ".btnOpenPoll", function(e){
        $scope.pid              =   parseInt($(this).data('pid'));
        $scope.isLoading        =   true;

        $http({
            method: 'POST',
            url: 'actions/polls/poll.php',
            data: {
                pid: $scope.pid
            }
        }).success(function(data,status,headers,config){
            if(data.status != 2){
                $("#pollModal").modal('hide');
                return null;
            }

            $scope.isLoading    =   false;
            $scope.poll         =   data.poll;

            if(data.votes > 0){
                $scope.alreadyAnswered  =   true;
                $scope.userAnswer       =   data.answer_key;
                angular.forEach($scope.poll.answers, function(value,key){
                    value.percentage    =   parseInt(value.total_votes / $scope.poll.total_votes * 100);
                });
            }
        });
    });

    $scope.selectAnswer         =   function(answer, $index){
        if($scope.alreadyAnswered){
            return null;
        }

        answer.total_votes++;
        $scope.poll.total_votes++;
        $scope.alreadyAnswered  =   true;
        $scope.userAnswer       =   $index;

        angular.forEach($scope.poll.answers, function(value,key){
            value.percentage    =   parseInt(value.total_votes / $scope.poll.total_votes * 100);
        });

        $http({
            method: 'POST',
            url: 'actions/polls/vote.php',
            data: {
                ai: $index,
                pid: $scope.pid
            }
        });
    };
}]);