/* global Utility, editor, bootstrap, Utils, UIProvider, koObservableController,
 PubSubController, Channels, Unit, CONST, LessController, _$ */
/* exported UIPSheetWidth */

/**
 * @param {ProviderData} data
 * @constructor
 */
function UIPSheetWidth(data) {
    'use strict';

    UIPSheetWidth.superclass.constructor.call(this, data);

    var containerChanged = ko.observable();

    var resize = function (width) {
        var containerInner = $('.' + CONST.CORE.CONTAINER_INNER_CLASS, editor.$previewBody),
            container = $('.' + CONST.CORE.CONTAINER_CLASS, editor.$previewBody);
        containerInner.css('max-width', width);
        container.css('width', width);

        PubSubController.once(Channels.history.requireCleanHtml, function () {
            if (containerInner) {
                containerInner.css('max-width', '');
            }
            if (container) {
                container.css('width', '');
            }
        });
    };

    this.value.dispose();
    this.value = ko.computed({
        read: function () {
            containerChanged();
            var size = Utility.getSheetSize();

            if (!this._valueChangeNotifier) {
                this._valueChangeNotifier = koObservableController.koBind(_$(window.bootstrap.variables));
            }
            this._valueChangeNotifier();

            return LessController.lessToCssValue(bootstrap.variables[size]);
        },
        write: function (value) {
            var unit = Unit.parse(value);
            var width = unit.size + unit.type;

            resize(width);

            var size = Utility.getSheetSize();

            bootstrap.variables[size] = width;

            PubSubController.publish(Channels.previewEvents.updated);
        },
        owner: this,
        deferEvaluation: true
    });

    this.updateWidthValue=function(arg) {
        containerChanged(arg.width);
    };

    PubSubController.subscribe(Channels.layoutMode.containerChanged, this.updateWidthValue);

}

Utils.extend(UIPSheetWidth, UIProvider);

UIPSheetWidth.prototype.dispose = function () {
    'use strict';
    UIPSheetWidth.superclass.dispose.call(this);
    PubSubController.unsubscribe(Channels.layoutMode.containerChanged, this.updateWidthValue);
};
