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

    angular.module('cla.quiz')
        .service('quizActions', quizActions);

    quizActions.$inject = ['quizTracker', 'quizResources', 'quizRedirect'];

    /**
     *
     * @constructor
     */
    function quizActions(quizTracker, quizResources, quizRedirect) {
        var service = {
            preview: false,
            setPreview: setPreview,

            start: start,
            finish: finish,
            next: next
        };

        return service;

        /**
         * sets preview mode on the resources service.
         */
        function setPreview(preview) {
            service.preview = preview;
            preview ? quizResources.enableInterceptor() : quizResources.disableInterceptor();
        }

        /**
         * start the quiz
         * @param {int} quiz_id
         * @param {function} callback
         */
        function start(quiz_id, callback) {
            // not loaded?
            if (!quizTracker.loaded) {
                // get questions
                quizResources.startQuiz(quiz_id).$promise.then(function (data) {
                    // promise success
                    quizTracker.init(data.questions, data.answers, {
                        showHelpText: data.showHelpText || false,
                        shuffleOptions: data.shuffleOptions || false
                    });
                    quizTracker.update();

                    // drop out to the callback
                    if (callback && typeof callback === 'function') {
                        callback(data);
                    }
                }, function (response) {
                    // promise failure
                    quizRedirect.toQuiz(quiz_id, response.data.message, true);
                });
            } else if (callback && typeof callback === 'function') {
                // quiz already initialised. simply drop out to the callback
                callback();
            }
        }

        /**
         * finish the quiz
         * @param {int} quiz_id
         * @param {function} callback
         */
        function finish(quiz_id, callback) {
            // do we have a payload. (i.e. do we have a chosen option)
            var payload = quizTracker.chosen[quizTracker.question];

            if (!payload)
                payload = {};

            // set extra payload params
            payload['question_id'] = quizTracker.currentQuestion.id;
            payload['complete'] = true;

            // execute finish quiz
            quizResources.finishQuiz(quiz_id, payload).$promise.then(function (data) {
                if (data.status == 1) {
                    // set results object
                    quizTracker.results = data.results;
                    quizTracker.can_retake = data.can_retake;
                    quizTracker.attempt_id = data.attempt_id;
                }

                if (callback && typeof callback === 'function') {
                    callback(data);
                }
            }, function (response) {
                quizRedirect.toQuiz(quiz_id, response.data.message, true);
            });
        }

        /**
         * move to the next question and submit the user's answer
         * @param {int} quiz_id
         */
        function next(quiz_id) {
            // do we want to update the user attempt?
            if (quizTracker.currentQuestion) {
                var question = quizTracker.question;

                // do we have a payload. (i.e. do we have a chosen option)
                if (quizTracker.chosen[question]) {
                    // evaluate question timer and update payload
                    var time_at_set = Date.now() - quizTracker.timer;
                    quizTracker.chosen[question].time_taken = time_at_set;

                    var payload = quizTracker.chosen[question];

                    (function (index) {
                        // submit payload for current quiz and question
                        quizResources.submitQuestion(quiz_id, quizTracker.currentQuestion.id, payload)
                            .$promise.then(function (data) {
                                // attempt has come back. add an argument to this callback to retrieve json data.
                                quizTracker.chosen[index].submitted = true;
                            },
                            function (response) {
                                quizRedirect.toQuiz(quiz_id, response.data.message, true);
                            }
                        );
                    })(question);
                }
            }
        }
    }
}());
