
(function () {
    'use strict';

    angular.module('cla.poll')
        .controller('introController', introController);

    introController.$inject = ['$scope', '$window', '$location', 'pollResources', 'pollTracker', 'pollRedirect', 'pollActions', 'growl.service'];

    /**
     *
     * @param $scope
     * @param $window
     * @param $location
     * @param pollResources
     * @param pollTracker
     * @param pollRedirect
     * @param pollActions
     * @param growlService
     * @constructor
     */
    function introController($scope, $window, $location, pollResources, pollTracker, pollRedirect, pollActions, growlService) {
        $scope.content = null;
        $scope.tracker = pollTracker;
        $scope.localise = localise;
        $scope.isContinue = isContinue;
        $scope.preview = $window.poll_preload.preview;
        $scope.poll_id = $window.poll_preload.poll.id;
        $scope.can_retake = true;
        $scope.has_just_voted = false;
        $scope.anonymous = false;
        $scope.has_voted_anonymously = false;
        $scope.hasEnded = hasEnded;
        $scope.showSubmit = showSubmit;
        $scope.showVoteAgain = showVoteAgain;
        $scope.showAlreadyVoted = showAlreadyVoted;
        $scope.showEndDate = showEndDate;
        $scope.showFinish = showFinish;
        $scope.toggleOption = toggleOption;
        $scope.isOptionSelected = isOptionSelected;
        $scope.isOptionHighlighted = isOptionHighlighted;
        $scope.getOptionLetter = getOptionLetter;
        $scope.voteAgain = voteAgain;
        $scope.next = next;
        $scope.finish = finish;
        $scope.viewResults = null;
        $scope.submit_disabled = false;
        $scope.showResults = showResults;
        $scope.votes = null;
        $scope.total = null;
        $scope.status = null;
        $scope.can_manage = false;

        $scope.canonicalUrl = $window.poll_preload.canonicalUrl;
        $scope.result_lmsg = '';
        $scope.end_date_lmsg = '';
        $scope.show_wrapper = false;
        $scope.vote_again = false;
        $scope.has_voted_again = false;
        $scope.outstandingRequests = 0;

        $scope.edit_poll_lmsg = lmsg('quiz.polls-surveys.edit_poll');
        $scope.view_results_lmsg = lmsg('quiz.survey.info.view_results');

        init();
        /**
         * initialise controller, with routing
         */
        function init() {

            var el  = angular.element('.js-link-edit');
            intro();
        }

        function intro() {
            $scope.isIE = /msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
            $scope.content = $window.poll_preload;
            $scope.anonymous = $scope.content.poll.anonymous;
            $scope.has_voted_anonymously = $scope.content.has_voted_anonymously;
            $scope.poll_title = $scope.content.poll.question[0].text;

            // Load more Quiz data from the API
            pollResources.getPoll($window.poll_preload.poll.id).$promise.then(function (data) {
                $scope.content = data;
                $scope.attempts_count = data.attempts_count;
                $scope.can_attempt = data.permissions.can_attempt;
                $scope.can_manage = data.permissions.can_manage;
                $scope.can_retake = data.permissions.can_retake;
                $scope.preview = $window.poll_preload.preview;
                $scope.viewResults = parseInt(data.poll.show_results);
                $scope.status = data.poll.status;
                $scope.end_date_lmsg = lmsg('quiz.poll.info.end_date', $scope.content.poll.end_date);

                if (hasEnded() && $scope.viewResults == 1)
                    $scope.viewResults = 2;

                $scope.completion = data.poll.completion_msg;
                if ($scope.completion === '')
                    $scope.completion = lmsg('quiz.poll.info.thank_you');

                if(
                    $scope.hasEnded() ||
                    ($scope.content.attempt && $scope.content.attempt.completed_date) ||
                    ($scope.anonymous && $scope.has_voted_anonymously) ||
                    $scope.status === 2
                )
                {

                    pollActions.getResults($scope.poll_id, function () {
                        $scope.votes = pollTracker.results.votes;
                        $scope.total = pollTracker.results.total;

                        $scope.result_lmsg = lmsg('quiz.poll.results', $scope.total);
                    });
                    showVoteAgain();

                }else
                {
                    start();
                }

            }, function (response) {
                pollRedirect.toPollList(response.data.message, true);
            });

        }

        function start() {
            pollActions.setPreview($scope.preview);
            pollActions.start($scope.poll_id, $scope.anonymous, function () {
                $scope.question = pollTracker.currentQuestion;
                $scope.optionIndexes = pollTracker.optionIndexes;
                // angular.element("#quiz-wrap").show();

                $scope.show_wrapper = true;
            });

            if (!$scope.can_attempt) {
                $scope.question = pollTracker.currentQuestion;
                $scope.optionIndexes = pollTracker.optionIndexes;
            }

            // angular.element("#quiz-wrap").show();
            $scope.show_wrapper = true;
            showVoteAgain();

        }

        /**
         * localisation
         * @returns {string}
         */
        function localise() {
            return String.localise.apply(this, arguments);
        }


        /**
         * @returns {boolean}
         */
        function isContinue() {
            return ($scope.content.attempt && !$scope.content.attempt.completed_date);
        }

        function hasEnded() {
            const endDateTime = new Date(poll_preload.poll.end_date_js)
            const endHour = endDateTime.getHours()
            const endMinutes = endDateTime.getMinutes()

            if (!$scope.content.poll.end_date) {
                return false
            }

            const endDate = new Date($scope.content.poll.end_date_js)
            endDate.setHours(endHour)
            endDate.setMinutes(endMinutes)

            return endDate < new Date()
        }

        function showEndDate() {
            if (!$scope.content.poll.end_date) {
                return false
            }

            return new Date($scope.content.poll.end_date_js) > new Date()
        }

        function showSubmit()
        {
            if ($scope.hasEnded())
                return false;

            if ($scope.content.attempt && $scope.content.attempt.completed_date)
                return false;

            return true;
        }

        function showAlreadyVoted() {

            if ($scope.content.attempt && $scope.content.attempt.completed_date)
                return true;

            if ($scope.anonymous && $scope.has_voted_anonymously)
                return true;

            return false;

        }

        function showVoteAgain() {

            if ($scope.hasEnded())
                return false;

            if (($scope.content.attempt && $scope.content.attempt.completed_date) && ($scope.content.permissions && $scope.content.permissions.can_retake))
            {
                $scope.vote_again = true;
            }


            if (($scope.anonymous && $scope.has_voted_anonymously) && ($scope.content.permissions && $scope.content.permissions.can_retake))
            {
                $scope.vote_again = true;
            }


            return false;

        }

        function showFinish() {
            if ($scope.has_just_voted)
            {
                return true;
            }


            return false;
        }

        function showResults() {
            if ($scope.has_just_voted || showAlreadyVoted())
            {
                return true;
            }

            return false;
        }


        /**
         * Set a selected option.
         *
         * Time taken is not tracked until we move to the next question, so this is set to null.
         *
         * @param {int} option_id
         */
        function toggleOption(option_id) {
            if ($scope.submit_disabled)
                return;

            pollTracker.toggleOption(option_id, null);

            $scope.outstandingRequests++;
            var promise = pollActions.next($scope.poll_id, $scope.anonymous);
            if (promise !== false)
            {
                promise.finally(function() {
                    $scope.outstandingRequests--;
                });
            }
        }

        function isOptionHighlighted(option_id) {
            return getOptionIndex(option_id) === pollTracker.highlightedIndex;
        }

        function isOptionSelected(option_id) {
            return pollTracker.isOptionChosen(pollTracker.question, option_id);
        }

        function getOptionIndex(option_id) {
            var optionIds = pollTracker.optionIndexes[pollTracker.currentQuestion.id];

            return optionIds.indexOf(option_id);
        }

        function getOptionLetter(index) {
            return String.fromCharCode(65 + index);
        }

        function next() {
            // $scope.submit_disabled = true;
            // pollActions.next($scope.poll_id, function () {
            //     $scope.submit_disabled = false;
            // });
        }

        function finish() {
            if (!$scope.submit_disabled && $scope.outstandingRequests === 0)
            {
                $scope.submit_disabled = true;
                if(!pollTracker.chosen[pollTracker.question] || pollTracker.chosen[pollTracker.question].options.length === 0)
                {
                    growlService.flash('Please select one option', null, true);
                    $scope.submit_disabled = false;
                    return;
                }
                pollActions.finish(pollTracker.attempt_id, function () {
                        $scope.has_just_voted = true;
                        if (!$scope.preview)
                        {
                            $scope.votes = pollTracker.results.votes;
                            $scope.total = pollTracker.results.total;
                            $scope.result_lmsg = lmsg('quiz.poll.results', $scope.total);
                        }

                        $scope.show_wrapper = false;
                        $scope.submit_disabled = false;
                        if ($scope.has_voted_again)
                            $scope.vote_again = true;

                });
            }
        }

        function voteAgain() {
            $scope.has_voted_again = true;
            $scope.vote_again = false;
            if ($scope.content.permissions && $scope.content.permissions.can_retake)
            {
                $scope.has_just_voted = false;
                $scope.content.attempt = false;
                $scope.has_voted_anonymously = false;
                pollTracker.loaded = false;
                $scope.optionIndexes = $scope.tracker.optionIndexes = {};
                $scope.show_wrapper = false;
                start();
            }

        }


    }
}());
