"use strict";

(function($) {
$.widget("cgpma.tickbox", {

    options: {
        value: null,
        baseValue: null,
    },

    _create : function() {
        var widget = this;
        widget.$element = this.element;
        widget.$element.disableSelection();
        widget.$tick = $.bem.generateElement("cgpma", "tickbox-tick");
        widget.$tick.appendTo(widget.$element);

        widget.$element.data("widget", widget);
        widget.$element.bind("click", widget.__handleTickClick);
    },

    _destroy : function() {
        this.$element.removeData();
    },

    _setOption: function (key, value) {
        var widget = this;

        // Check if such option exists, throw an error if not
        if (!widget.options.hasOwnProperty(key)) {
            throw "Option " + key + " does not exist";
        }

        // Check if value matches what it was, do nothing if yes
        if (value === widget.options[key] || (_.isArray(value) && _.isEqual(value, widget.options[key]))) {
            return;
        }

        // Save old option value
        var prev = widget.options[key];

        // Apply the option
        widget._super(key, value);

        // Call corresponding update method depending on the option key
        switch (key) {

        case "value":
            widget._applyValue();
            break;

        case "baseValue":
            widget._updateStatus();
            break;
        }

        widget._trigger("change" + key.toLowerCase(), null, {newValue: value, prevValue: prev});
    },

    _applyValue: function() {
        var widget = this;
        widget.$element.toggleClass("cgpma__tickbox_ticked", !!widget.options.value);
        widget._updateStatus();
    },

    _updateStatus: function() {
        var widget = this;
        widget.$element.toggleClass("cgpma__tickbox_status_modified", !!widget.options.baseValue != !!widget.options.value);
    },

    __handleTickClick: function() {
        var $this = $(this);
        var widget = $this.data("widget");
        var newValue = widget.options.value ? "" : "1";
        if (newValue == "" && $this.hasClass("cgpma__tickbox_type_radio")) {
            return;
        }
        widget._setOption("value", newValue);
    },
});
})(jQuery);