define(['jquery'], function ($) {
    /**
     *
     * @constructor
     */
    var PollComponent = function (poll_body, poll_id, question_id, anonymous) {

        this.option_id = null;
        this.attempt_id = null;

        this.poll_id = poll_id;
        this.question_id = question_id;
        this.anonymous = anonymous;

        this.poll_body = poll_body;

        this.vote_container = this.poll_body.find('#container-vote');
        this.vote_button = this.vote_container.find('button[name="vote-form-button"]');
        this.option_buttons = this.vote_container.find('cla-item[name="option_id"]');
        this.view_results_button = this.vote_container.find('button[name="view_results_button"]');

        this.results_container = this.poll_body.find('#vote-results');
        this.no_results_container = this.poll_body.find('#no-results');
        this.result_bars = this.results_container.find('cla-progress[name="progress"]');
        this.revote_button = this.results_container.find('button[name="revote_button"]');
        this.revote_button_no_result = this.poll_body.find('#results_never_revote');

        this.registerEventListeners();
    };

    /**
     * update results after click
     * @param results
     */
    PollComponent.prototype.showResults = function (results) {
        this.showOptions(false);

        if (!results.can_view) {
            this.showNoResults();
            return;
        }

        this.result_bars.each(function () {
            var vote_id = $(this).prop('id').replace('progress_', '');
            var that = this;

            $(this).prop('minimum', 0);
            $(this).prop('maximum', results.total);

            // This delay is here due to a bug in the cla-progress component
            // please remove it if the bug has been fixed
            setTimeout(function(){
                $(that).prop('current', results.votes[vote_id].count);
            }, 100);
            $(this).text(results.votes[vote_id].count);
        });
    };

    PollComponent.prototype.duplicateAttempt = function() {
        var self = this;
        cla.showMessage(lmsg('quiz.poll_component.bad_attempt'), null, true);
        $.ajax({
            type: 'GET',
            url: '/api/quiz/v2/polls/' + self.poll_id + '/results',
            contentType: 'application/json'
        }).done(function(data){
            self.showResults(data.results);
        });
    };

    PollComponent.prototype.disablePicker = function() {
        this.poll_body.find("cla-picker").prop("disabled", true);
    };

    PollComponent.prototype.enablePicker = function () {
        this.option_buttons.find("cla-picker").prop("disabled", false);
    };

    PollComponent.prototype.uncheckOptions = function () {
        this.option_buttons.find("cla-picker").prop("checked", false);
    };

    PollComponent.prototype.registerEventListeners = function () {
        var self = this;

        this.option_buttons.on('click', function (e) {
            e.preventDefault();
            self.option_id = $(this).attr('id');

            if ($(this).find("cla-picker").prop("disabled"))
                return false;

            // attempt to poll
            $.post('/api/quiz/v2/polls/' + self.poll_id + '/attempts',
                JSON.stringify({anonymous: parseInt(self.anonymous)}),
                function (data) {
                    if (parseInt(data.status) === 1) {
                        self.attempt_id = data.attempt.id;
                    }
                }).done(function () {
                // answer
                $.ajax({
                    type: 'POST',
                    url: '/api/quiz/v2/attempts/' + self.attempt_id + '/answers',
                    contentType: 'application/json',
                    data: JSON.stringify([{
                        options: [self.option_id],
                        time_taken: 123,
                        submitted: false,
                        question_id: parseInt(self.question_id),
                        anonymous: parseInt(self.anonymous)
                    }]),
                    success: function () {
                        self.vote_button.prop('disabled', false);
                    }
                });
            }).fail(function () {
                self.disablePicker();
                self.duplicateAttempt();
            });
        });

        // send ajax request
        this.vote_button.on('click', function () {
            $(this).prop("disabled", true);
            self.disablePicker();
            $.ajax({
                type: 'PUT',
                url: '/api/quiz/v2/attempts/' + self.attempt_id,
                contentType: 'application/json',
                data: JSON.stringify({
                    options: [self.option_id],
                    time_taken: 200,
                    submitted: true,
                    question_id: parseInt(self.question_id),
                    anonymous: parseInt(self.anonymous),
                    complete: true,
                }),
                success: function (res) {
                    return res;
                }
            }).done(function (res) {
                if (res.thank_msg)
                    cla.showMessage(res.thank_msg);

                self.showResults(res.results);
                self.enablePicker();
                self.uncheckOptions();
                self.revote_button_no_result.removeClass('d-none');
            }).fail(function () {
                self.duplicateAttempt();
            });
        });

        this.revote_button.on('click', function () {
            self.showOptions(true);
        });

        this.revote_button_no_result.on('click', function () {
            self.revote_button_no_result.addClass('d-none');
            self.showOptions(true);
        });

        this.view_results_button.on('click', function () {
            self.showOptions(false);
        });
    };

    PollComponent.prototype.showOptions = function (show_options) {
        if (show_options) {
            this.results_container.addClass('d-none');
            this.vote_container.removeClass('d-none');
        } else {
            this.vote_container.addClass('d-none');
            this.results_container.removeClass('d-none');
        }
    };

    PollComponent.prototype.showNoResults = function () {
            this.results_container.addClass('d-none');
            this.no_results_container.removeClass('d-none');
    };

    return PollComponent;
});
