/**
 * Controls the taking of a quiz
 *
 * @author Simon Willan <simon.willan@claromentis.com>
 */
(function () {
    'use strict';

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

    introController.$inject = ['$scope', '$window', 'quizResources', 'quizTracker', 'quizRedirect'];

    /**
     *
     * @param $scope
     * @param $window
     * @param quizResources
     * @param quizTracker
     * @param quizRedirect
     * @constructor
     */
    function introController($scope, $window, quizResources, quizTracker, quizRedirect) {
        $scope.content = null;
        $scope.tracker = quizTracker;
        $scope.localise = localise;
        $scope.attemptsTemplate = attemptsTemplate;
        $scope.maxAttemptsReached = maxAttemptsReached;
        $scope.isContinue = isContinue;

        $scope.preview = $window.quiz_preload.preview;
        $scope.quiz_id = $window.quiz_preload.quiz.id;
        $scope.can_retake = true;
        $scope.preview = false;

        $scope.canonicalUrl = $window.quiz_preload.canonicalUrl;

        init();

        /**
         * initialise controller, with routing
         */
        function init() {
            angular.element("#quiz-wrap").hide();

            intro();
        }

        function intro() {
            $scope.content = $window.quiz_preload;

            // Load more Quiz data from the API
            quizResources.getQuiz($window.quiz_preload.quiz.id).$promise.then(function (data) {
                $scope.content = data;
                $scope.attempts_count = data.attempts_count;
                $scope.can_attempt = data.permissions.can_attempt;
                $scope.can_retake = data.permissions.can_retake;
                $scope.preview = $window.quiz_preload.preview;
            }, function (response) {
                quizRedirect.toQuizList(response.data.message, true);
            });

            angular.element("#quiz-wrap").show();
        }

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

        /**
         *
         * @returns {string}
         */
        function attemptsTemplate() {
            return '/quiz/' + $window.quiz_preload.quiz.id + '/template'
        }

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

        /**
         * has the user reached maximum attempts for this quiz.
         * @returns {boolean}
         */
        function maxAttemptsReached() {
            return ($scope.attempts_count > 0 &&
                !$scope.can_retake &&
                !$scope.preview &&
                !$scope.content.quiz.is_archived &&
                !isContinue());
        }
    }
}());
