/* global $, Utility, UIProvider, editor, UIProvider, Style, ComponentStyles, koObservableController, SerializeController,
   PubSubController, Channels, MixinsController */
/**
 * @param {ProviderData} data
 * @constructor
 */
var UIPUseDefaultComponent = function UIPUseDefaultComponent(data) {
    'use strict';
    UIPUseDefaultComponent.superclass.constructor.call(this, data);

    var currentTemplate = ko.observable();

    function updateCurrentTemplate() {
        currentTemplate(editor.templatesController.currentTemplate);
    }

    updateCurrentTemplate();

    this.value = ko.computed({
        read: function () {
            if (!this._valueChangeNotifier) {
                this._valueChangeNotifier = koObservableController.koBind(this.control(), '', function (control){
                    return MixinsController.isProxy(control);
                });
            }
            return this._valueChangeNotifier();
        },
        write: function (value) {
            var control = this.control();
            var template = currentTemplate(),
                componentKey = template.templateName + 'component';
            if (value === true) {
                if ('undefined' !== $.data(template, componentKey)) {
                    SerializeController.fillFromObject($.data(template, componentKey), control.componentStyles);
                }
                control.componentStyles = new Style('Component');
            } else {
                if ('undefined' === typeof $.data(template, componentKey)) {
                    $.data(template, componentKey, new ComponentStyles());
                }
                control.componentStyles = $.data(template, componentKey);
            }

            editor.stackCache.buildCache();
        },
        owner: this
    });

    PubSubController.subscribe(Channels.template.changed, updateCurrentTemplate);

    this.dispose = function () {
        UIPUseDefaultComponent.superclass.dispose.call(this);
        PubSubController.unsubscribe(Channels.template.changed, updateCurrentTemplate);
    };
};

Utility.extend(UIPUseDefaultComponent, UIProvider);