/* global Utility, editor, bootstrap, Utils, UIProvider, koObservableController,
PubSubController, Channels, CssUtility, CONST */
/* exported UIPSheetWidth */

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

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

    var containerChanged = ko.observable();

    this.value = ko.computed({
        read: function () {
            containerChanged();
            var size = Utility.getSheetSize(window.bootstrap, editor.documentContent.width());

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

            var width = CssUtility.parseUnit(window.bootstrap.variables.lessToCssValue(bootstrap.variables[size])).size;

            return width;
        },
        write: function (value) {
            var unit = CssUtility.parseUnit(value);
            var width = unit.size + unit.type;

            var containerInner = $('.' + CONST.CORE.CONTAINER_INNER_CLASS, editor.documentBody);
            containerInner.css('max-width', width);

            var size = Utility.getSheetSize(window.bootstrap, editor.documentContent.width());

            bootstrap.variables[size] = width;

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

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

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

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

}

Utils.extend(UIPSheetWidth, UIProvider);
