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

    angular.module('cla.survey').controller('finishController', finishController);
    finishController.$inject = ['$scope', '$window', '$route', 'surveyTracker', 'surveyResources', 'surveyRedirect'];

    /**
     *
     * @param $scope
     * @param $window
     * @param $route
     * @param surveyTracker
     * @param surveyResources
     * @param surveyRedirect
     * @constructor
     */
    function finishController($scope, $window, $route, surveyTracker, surveyResources, surveyRedirect) {
        $scope.content = null;
        $scope.results = null;
        $scope.questions = null;
        $scope.can_retake = true;
        $scope.attempt_id = null;
        $scope.completition_msg = null;

        $scope.localise = localise;
        $scope.retake = retake;
        $scope.answersTemplate = answersTemplate;

        $scope.survey_id = $window.survey_preload.survey.id;
        $scope.canonicalUrl = $window.survey_preload.canonicalUrl;
        $scope.preview = $window.survey_preload.preview;

        window.onbeforeunload = null;


        init();

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

            results();
        }

        /**
         * update the results if nothing has been set on this page.
         */
        function results() {
                angular.element("#survey-wrap").hide();

                surveyResources.getResults($scope.survey_id, surveyTracker.attempt.id).$promise.then(function(data) {
                    surveyTracker.results = data.results;
                    $scope.results = data.results;
                    $scope.can_retake = data.can_retake;
                    $scope.attempt_id = data.attempt_id;
                    $scope.completition_msg = data.completion_msg;
                    $scope.content = $window.survey_preload.survey;
                    $scope.questions = surveyTracker.questions;
                    $scope.answers = surveyTracker.chosen;

                    angular.element("#survey-wrap").show();
                }, function(response) {
                    surveyRedirect.toSurvey($scope.survey_id, response.data.message, true);
                });

        }

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

        /**
         * goes back to survey intro page
         */
        function retake() {
            surveyTracker.init(surveyTracker.questions);
            surveyTracker.update();

            $window.location.href = `/survey/${$scope.survey_id}`;
        }

        /**
         * fetches the answers datatable template
         */
        function answersTemplate() {
            if ($scope.attempt_id) {
                return `/survey/attempt/${$scope.attempt_id}/template`;
            }
        }
    }
}());
