/**
 * Controls the survey results
 */
(function () {
    'use strict';

    const PAGE_TYPE_INDIVIDUAL = 0;
    const PAGE_TYPE_SUMMARY = 1;

    angular.module('cla.survey').controller('resultController', resultController);

    resultController.$inject = ['$scope', '$window', '$route', '$routeParams', 'surveyResources', 'surveyRedirect'];

    function resultController($scope, $window, $route, $routeParams, surveyResources, surveyRedirect) {
        if (!$window.survey_preload.can_view_results) {
            surveyRedirect.toSurveyList(lmsg('quiz.survey.error.no_results_perms'), true);
        }

        $scope.attempts = null;
        $scope.answers = null;
        $scope.survey_id = $window.survey_preload.survey.id;
        $scope.content =  $window.survey_preload.survey;
        $scope.can_manage = $window.survey_preload.can_manage;
        $scope.can_view_results = $window.survey_preload.can_view_results;
        $scope.initial_attempt = $routeParams.attempt || null;

        if (!$scope.can_view_results)
        {
            surveyRedirect.redirect('/polls-surveys', lmsg('quiz.survey.error.no_stats_perms'), true);
            return;
        }

        $scope.result_page = [
            {value: PAGE_TYPE_INDIVIDUAL, name: lmsg('quiz.survey.stats.individual'), selected: 'Selected'},
            {value: PAGE_TYPE_SUMMARY, name: lmsg('quiz.survey.stats.summary'), selected: false}
        ];

        $scope.result_page_data = $scope.result_page[0]

        /**
         * return true if option has been chosen by user
         * @param question_id
         * @param option_id
         * @returns {*|boolean}
         */
        $scope.isAnswer = function(question_id, option_id) {
            if ($scope.answers !== null && $scope.answers.hasOwnProperty(question_id)) {
                return $scope.answers[question_id].properties.response.hasOwnProperty(option_id);
            }

            return false;
        }

        /**
         * return typed answer text
         * @param question_id
         * @returns {boolean|*}
         */
        $scope.isTextAnswer = function(question_id) {
            if ($scope.answers !== null && $scope.answers.hasOwnProperty(question_id)) {
                if ($scope.answers[question_id].properties.response_text !== null) {
                    return $scope.answers[question_id].properties.response_text;
                }

                return $scope.answers[question_id].properties.response;
            }

            return '';
        }

        $scope.getAttempt = function(attempt_id) {
            // get survey results from API
            surveyResources.getResults($scope.content.id, attempt_id).$promise
                .then(res => {
                    $scope.answers = res.answers;
                })
                .catch(e => cla.showMessage(e.toString(), null, true));
        }

        /**
         * changed result type summary/individual
         */
        $scope.resultTypeChanged = function(page_type) {
            if (page_type === PAGE_TYPE_SUMMARY) {
                window.location.href = window.location.href.replace('#/results/individual', '/results');
            }
        }



        init();

        function init() {
            // init select with all users attempts
            $scope.isIE = /msie\s|trident\/|edge\//i.test(window.navigator.userAgent);
            surveyResources.getAttempts($scope.content.id).$promise
                .then(res => {
                    $scope.attempts = res;

                    // add selected prop to model
                    angular.extend($scope.attempts, {selected: res.attempts[0]})

                    // add complete date to select element
                    if ($scope.attempts.attempts !== null || $scope.attempts.attempts[Symbol.iterator] === 'function') {
                        $scope.attempts.attempts.map(attempt => angular.extend(attempt.user, {name_date: `${attempt.user.name} [${attempt.completed_date}]`}))
                    }

                    // if the user visited a link to a specific result, make that one be selected
                    if ($scope.attempts.attempts !== null && $scope.initial_attempt != null) {
                        for (var i = 0; i < $scope.attempts.attempts.length; i++) {
                            var attempt = $scope.attempts.attempts[i];

                            if (attempt.id == $scope.initial_attempt) {
                                $scope.attempts.selected = attempt;
                                break;
                            }
                        }
                    }

                    if (res.selected !== undefined && res.hasOwnProperty('selected')) {
                        return res.selected.id
                    }

                    return null;
                })

                .then(id => {
                    // call get attempts for default user
                    if (id !== null) {
                        $scope.getAttempt(id)
                    }
                })

                .catch(e => cla.showMessage(e.toString(), null, true))
        }
    }
}());
