/*global koObservableController, Utility, UIProvider, editor,
MixinsController, UIProvider, PubSubController, Channels */

/**
 * @param {ProviderData} data
 * @constructor
 */
var UIPPageBackground = function UIPPageBackground(data) {
    'use strict';
    UIPPageBackground.superclass.constructor.call(this, data);

    var currentTemplate = ko.observable();
    var bodySubscription;

    function updateCurrentTemplate() {
        currentTemplate(editor.templatesController.currentTemplate);
        if (bodySubscription)
            koObservableController.koUnbind(bodySubscription);
        bodySubscription = koObservableController.koBind(null, null, updateControl);
    }

    var updateControl = function () {
        var pageBG = currentTemplate().BaseTemplate.body.pageBackground;
        this.control(MixinsController.isProxy(pageBG) ?
            MixinsController.getCategoryMixin(pageBG) :
            pageBG);
    }.bind(this);

    updateCurrentTemplate();

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

    this.dispose = function () {
        UIPPageBackground.superclass.dispose.call(this);
        koObservableController.koUnbind(bodySubscription);
        PubSubController.unsubscribe(Channels.template.changed, updateCurrentTemplate);
    };
};

Utility.extend(UIPPageBackground, UIProvider);