/**
 * Controls the taking of a survey
 */
(function () {
    'use strict';

    angular.module('cla.survey').service('surveyActions', surveyActions);

    surveyActions.$inject = ['surveyResources', 'surveyTracker', 'surveyRedirect', 'growl.service'];

    var outstandingRequests = 0;

    /**
     * @constructor
     */
    function surveyActions(surveyResources, surveyTracker, surveyRedirect, growlService) {
        let service = {
            preview: false,
            /**
             * sets preview mode on the resources service.
             */
            setPreview: function(preview) {
                service.preview = preview;
                preview ? surveyResources.enableInterceptor() : surveyResources.disableInterceptor();
                surveyTracker.preview = preview;
            },

            /**
             * Attempt to survey
             *
             * @param survey_id
             * @param anonymous
             * @param callback
             */
            start: function(survey_id, anonymous = false, callback) {
                // not loaded?
                if (!surveyTracker.loaded) {
                    // get questions
                    surveyResources.startSurvey(survey_id, anonymous).$promise
                        .then(function(data) {
                            let questions = []

                            data.sections.map(section => {
                                Object.assign(questions, section.questions)
                            })

                            surveyTracker.init(data.sections, data.answers, {showHelpText: data.showHelpText || false, shuffleOptions: data.shuffleOptions || false}, data.attempt);
                            surveyTracker.update();

                            // drop out to the callback
                            if (callback && typeof callback === 'function') {
                                callback(data);
                            }
                        }, function (response) {
                            // promise failure
                            surveyRedirect.toSurvey(survey_id, response.data.message, true);
                        });
                } else if (callback && typeof callback === 'function') {
                    // survey already initialised. simply drop out to the callback
                    callback();
                }
            },

            /**
             * finish the survey
             * @param {int} survey_id
             * @param {bool} anonymous
             * @param {function} callback
             */
            finish: function(survey_id, callback) {
                if (!surveyTracker.areAllMandatoryQuestionsAnswered())
                {
                    var count = surveyTracker.unansweredMandatoryQuestionsCount();
                    growlService.showError(lmsg('quiz.survey.error.some_questions_unanswered', count));

                    return false;
                }

                // execute finish survey
                surveyResources.finishSurvey(surveyTracker.attempt.id, surveyTracker.anonymous).$promise.then(function (data) {
                    if (data.status == 1) {
                        // set results object
                        surveyTracker.results = data.results;
                        surveyTracker.can_retake = data.can_retake;
                        surveyTracker.attempt_id = data.attempt_id;
                    }

                    if (callback && typeof callback === 'function') {
                        callback(data);
                    }
                }, function (response) {
                    // surveyRedirect.toSurvey(survey_id, response.data.message, true);
                });
            },

            /**
             * move to the next question and submit the user's answer
             * @param {int} survey_id
             */
            next: function(survey_id) {
                // current section object
                if (surveyTracker.currentSection) {
                    let sectionId = surveyTracker.question;
                    // surveyTracker.sections[sectionId] = surveyTracker.currentSection

                    // do we have a payload. (i.e. do we have a chosen option)
                    if (surveyTracker.chosen[sectionId]) {
                        let time_at_set = Date.now() - surveyTracker.timer;
                        surveyTracker.chosen.time_taken = time_at_set;
                    }
                }
            },

            /**
             * Submit answer
             *
             * @param survey_id
             * @param is_anonymous - when answer is anonymous
             * @param question_id
             * @param answer_id
             * @param answers
             */
            answer: function(survey_id, question_id, answer_id, answers) {
                outstandingRequests++;

                surveyTracker.toggleOption(question_id, answer_id);

                surveyTracker.chosen[question_id].time_taken = Date.now() - surveyTracker.timer
                surveyTracker.chosen[question_id].anonymous = surveyTracker.anonymous;

                let answer = {
                    response: (typeof answers === 'string' || Array.isArray(answers)) ? answers : [answers.id],
                    question_id: question_id,
                    submitted: true,
                    time_taken: Date.now() - surveyTracker.timer,
                    anonymous: surveyTracker.anonymous
                };

                // submit payload for current survey and question
                return surveyResources.submitQuestion(surveyTracker.attempt.id, [answer]).$promise.then(data => {
                        // attempt has come back. add an argument to this callback to retrieve json data.
                        if (data.status === 1 || data.status === 'intercepted') {
                            surveyTracker.chosen.submitted = true;

                            // push answer to tracker answers array
                            surveyTracker.mergeAnswer(answer);
                            /*if (surveyTracker.answers.filter(answer => answer.question_id === answer.id)) {
                                surveyTracker.answers.push(answer)
                            }*/
                        }
                    },
                    response => surveyRedirect.toSurvey(survey_id, response.data.message, true)
                ).finally(function(){outstandingRequests--});
            }
        };

        return service;
    }
}());
