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

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

    surveyInterceptor.$inject = ['$resource', '$q'];

    /**
     *
     * @param $resource
     * @param $q
     * @constructor
     */
    function surveyInterceptor($resource, $q) {
        const service = {
            start: start,
            submit: submit,
            finish: finish,
            survey: survey,
            results: results
        };

        return service;

        /**
         * call a different endpoint when starting with interceptor. just retrieve the list of questions
         * @param defaults
         * @param options
         * @returns {*}
         */
        function start(defaults, options) {
            return $resource('/api/quiz/v2/surveys/:id/sections', {}, {sections: {}})
                .sections(defaults, options);
        }

        /**
         * create a fake promise and resolve with an empty object
         * @returns {{$promise: *}}
         */
        function submit() {
            let defer = $q.defer();
            defer.resolve({status: 'intercepted'});

            return {$promise: defer.promise};
        }

        /**
         * create a fake promise and resolve with an empty object
         * @returns {{$promise: *}}
         */
        function results(defaults, options)
        {
            return $resource('/api/quiz/v2/surveys/:id/preview', {}, {results: {}})
                .results(defaults, options);
        }

        /**
         * create a fake promise and resolve with an object with status of 0
         * @returns {{$promise: *}}
         */
        function finish() {
            let defer = $q.defer();
            defer.resolve({status: 0});

            return {$promise: defer.promise};
        }

        /**
         * call the survey endpoint just as in resource. We don't need to skip this one
         * @param defaults
         * @param options
         * @returns {*}
         */
        function survey(defaults, options) {
            return $resource('/api/quiz/v2/surveys/:id', {}, {survey: {}}).survey(defaults, options);
        }
    }

}());
