/**
 * Created by jaskokoyn on 4/26/2015.
 */
owlChatApp.controller("pollCenterCtrl", ["$scope", "$rootScope", "$http", "$timeout", function($scope, $rootScope, $http, $timeout){
    $scope.isCreatingPoll               =   false;
    $scope.polls                        =   [];
    $scope.createPollObj                =   {
        question: null,
        answers: []
    };

    $http({
        method: 'POST',
        url: 'actions/polls/get-polls.php'
    }).success(function(data,status,headers,config){
        data.polls.forEach(function(ele,ind,arr){
            $scope.polls.push(ele)
        });

        $timeout(function(){
            $(".btnTooltip").tooltip();
        }, 500);
    });

    $scope.addAnswer                    =   function(){
        $scope.createPollObj.answers.push({
            answer: null,
            total_votes: 0
        });
    };

    $scope.createPoll                   =   function(){
        $("#createPollForm").slideUp('fast', function(){
            $("#createPollStatus").html(
                '<div class="alert alert-info">Creating Poll. Please wait.</div>'
            );

            $http({
                method: 'POST',
                url: 'actions/polls/create.php',
                data: $scope.createPollObj
            }).success(function(data,status,headers,config){
                if(data.status == 1){
                    $("#createPollStatus").html(
                        '<div class="alert alert-info">Unable to create poll. Try again later.</div>'
                    );
                    $("#createPollForm").slideDown('fast');
                    return null;
                }

                $("#createPollForm").show();
                $("#createPollStatus").hide();
                $scope.isCreatingPoll               =   false;
                $scope.polls.push(data.poll);

                $timeout(function(){
                    $(".btnTooltip").tooltip();
                }, 500);
            });
        });
    };

    $scope.deletePoll                   =   function(poll, $index){
        if(confirm("Are you sure you want to do this? This action can not be undone.")){
            $scope.polls.splice($index, 1);

            $http({
                method: 'POST',
                url: 'actions/polls/delete-poll.php',
                data: poll
            });
        }
    };

    $scope.addPollToChat                =   function(poll){
        if(typeof $rootScope.last_cid === "undefined"){
            return null;
        }

        $("#pollCenterModal").modal('hide');

        $http({
            method: 'POST',
            url: 'actions/polls/add-poll-chat.php',
            data: {
                pid: poll.id,
                cid: $rootScope.last_cid
            }
        });
    };
}]);