jscape.domain = jscape.domain || {};

/** @class */
jscape.WebTheme = Class.extend(
    /** @lends {jscape.WebTheme.prototype} */
{
    /** @constructor */
    initialize: function(a, b, c, d, e) {
        this.name = a || "";
        this.owner = b || "";
        this.encodedLogo = c || "";
        this.uri = d || "";
        this.tags = e || [];
    }
});
jscape.WebTheme.fromJSON = function(data) {
    return data ? new jscape.WebTheme(data.name, data.owner, data.encodedLogo, data.uri, data.tags) : null;
};

/** @class */
jscape.domain.UrlBrandingModule = jscape.domain.DomainModule.extend(
    /** @lends {jscape.domain.UrlBrandingModule.prototype} */
{
    onCreate: function() {
        this._super.apply(this, arguments);

        this.controller = new jscape.domain.UrlBrandingController();
        this.controller.onCreate(this.managementService, this.domainName);
    },

    onStart: function () {
        this.controller.onStart();
    },

    onResume: function() {
        this.controller.onResume();
    }
});

/** @class */
jscape.domain.UrlBrandingController = jscape.ui.DatagridController.extend(
    /** @lends {jscape.domain.UrlBrandingController.prototype} */
{
    view: null,

    /** @constructor */
    initialize: function() {
        this._initValidators();
    },

    onCreate: function (managementService, domainName) {
        this.managementService = managementService;
        this.domainName = domainName;

        this.addController = new jscape.domain.AddUrlBrandingController();
        this.editController = new jscape.domain.EditUrlBrandingController();
        this.deleteController = new jscape.domain.DeleteUrlBrandingController();
    },

    onStart: function () {
        if (this.view == null) {
            this.view = new jscape.domain.UrlBrandingView();
        }
        this.view.show(this);
    },

    onResume: function () {
        this.view.refresh();
    },

    onRefresh: function(params) {
        params = jscape.Page.requestParameters(params);
        return this.managementService.listWebThemes(this.domainName, params.startIndex, params.count, params.query)
                .then(jscape.Page.datagridFormatter());
    },

    onAddTheme: function() {
        this.addController.start(this.managementService, this.domainName)
                .done($.proxy(this._themeAdded, this));
    },

    onEditTheme: function(theme) {
        var index = $.inArray(theme, this.view.getWebThemes());
        if (index != -1) {
            this.editController.start(this.managementService, this.domainName, theme)
                    .done($.proxy(this._themeEdited, this, index));
        }
    },

    onDeleteTheme: function(theme) {
        this.deleteController.start(this.managementService, this.domainName, theme)
                .done($.proxy(this._themeDeleted, this, theme));
    },

    _themeAdded: function (theme) {
        this._recordAdded(theme);
    },

    _themeEdited: function (index, theme) {
        this._recordEdited(theme);
    },

    _themeDeleted: function (themes) {
        this._recordDeleted(themes);
    },

    _initValidators: function () {
        var v = new jscape.Validator();
        v.rule("webtheme_name", $.proxy(this._themeNameValid, this), window.R.string.WEB_THEME_ERROR_BAD_NAME);
        v.rule("webtheme_unique", $.proxy(this._themeNotExists, this), window.R.string.WEB_THEME_ERROR_ALREADY_EXIST);
        v.rule("webtheme_logo", $.proxy(this._logoLoaded, this), window.R.string.WEB_THEME_ERROR_LOAD_LOGO);
    },

    _themeNameValid: function(name) {
        return name != null && /^[a-zA-Z0-9]+$/i.test(name);
    },

    _themeNotExists: function (name) {
        var values = $.map(this.view.getWebThemes(), function (theme) { return theme.name == name; });
        return $.inArray(name, values) == -1;
    },

    _logoLoaded: function(_, params) {
        return !!$(params[0]).data("logo_loaded");
    }
});

/** @class */
jscape.domain.UrlBrandingView = jscape.ui.DatagridView.extend(
    /** @lends {jscape.domain.UrlBrandingView.prototype} */
{
    selection: null,

    /** @constructor */
    initialize: function() {
        var initializing = true;

        this.fieldset = $("fieldset[name=urlbrandingfields]");

        this.data = $("table[role=grid][aria-label=urlbranding]", this.fieldset);
        this.data.datagrid({
            fit: true,
            fitColumns: true,
            singleSelect: true,
            pagination: true,
            search: true,
            remoteSearch: true,
            remoteSort: true,
            sortName: "name",
            idField: "name",
            columns: [[
                {field: "name", title: $("thead th:nth-child(1)", this.data).text(), sortable: true, width: 90},
                {field: "owner", title: $("thead th:nth-child(2)", this.data).text(), sortable: true, width: 90},
                {field: "uri", title: $("thead th:nth-child(3)", this.data).text(), searchable: false, width: 110},
                {field: "tags", title: $("thead th:nth-child(4)", this.data).text(), width: 80, formatter: function(value) { return String($.isArray(value) ? value.join(", ") : value).escapeXml(); }}
            ]],
            onSelect: $.proxy(this._adjustRowSelection, this),
            onUnselect: $.proxy(this._adjustRowSelection, this),
            onDblClickRow: $.proxy(this._onClick$EditButton, this),
            loader: $.proxy(this._onLoad$Data, this),
            onBeforeLoad: function () { return !initializing; },
            onLoadSuccess: $.proxy(this._adjustRowSelection, this)
        });

        this.addButton = $("a[role=button][name=add]", this.fieldset).linkbutton({onClick: $.proxy(this._onClick$AddButton, this)});
        this.editButton = $("a[role=button][name=edit]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$EditButton, this)});
        this.deleteButton = $("a[role=button][name=delete]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$DeleteButton, this)});
        this.logoButton = $("a[role=button][name=logo]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$LogoButton, this)});

        initializing = false;
    },

    show: function(listener) {
        this.listener = listener || jscape.domain.UrlBrandingView.LISTENER;
        this._adjustRowSelection();
    },

    getWebThemes: function() {
        return this.getRecords();
    },


    _onLoad$Data: function(params, success, error) {
        this.listener.onRefresh(params).done(success).fail(error);
    },

    _onClick$AddButton: function() {
        this.listener.onAddTheme();
    },

    _onClick$EditButton: function() {
        this.listener.onEditTheme(this.selection[0]);
    },

    _onClick$DeleteButton: function() {
        this.listener.onDeleteTheme(this.selection);
    },

    _onClick$LogoButton: function() {
        var theme = this.data.datagrid("getSelected");
        var row = this.data.datagrid("options").finder.getTr(this.data[0], null, "selected").find("td:first");
        row.tooltip({position: "bottom", content: "<img src=\"data:image/png;base64," + theme.encodedLogo + "\"/>"}).tooltip("show");
        this.logoButton.one("mouseleave", $.proxy(function() { row.tooltip("destroy"); }, this));
    },

    _adjustRowSelection: function () {
        this.selection = this.data.datagrid("getSelections");
        this._adjustButtonsState();
    },

    _adjustButtonsState: function() {
        this.editButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.logoButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.deleteButton.linkbutton(this.selection.length != 0 ? "enable" : "disable");
    }
});
jscape.domain.UrlBrandingView.LISTENER = {
    onRefresh: $.noop,
    onAddTheme: $.noop,
    onEditTheme: $.noop,
    onDeleteTheme: $.noop
};

/** @class */
jscape.domain.AddUrlBrandingController = Class.extend(
    /** @lends {jscape.domain.AddUrlBrandingController.prototype} */
{
    deferred: null,

    start: function(managementService, domainName) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this._setupDialog().show(this);
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var theme = this._createWebTheme(dialog);
        dialog.destroy();

        this.managementService.addWebTheme(this.domainName, theme)
                .done($.proxy(function(theme) { this.deferred.resolve(theme); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    },


    onCancel: function(dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    getWebThemeURI: function (themeName) {
        return themeName && themeName.trim().length
               ? this.managementService.getWebThemeURI(this.domainName, themeName)
               : $.Deferred().resolve("").promise();
    },

    _createWebTheme: function(dialog) {
        return new jscape.WebTheme(dialog.getName(),
                                   dialog.getOwner(),
                                   dialog.getLogoData(),
                                   null,
                                   dialog.getTags());
    },

    _setupDialog: function() {
        var dialog = new jscape.domain.AddUrlBrandingDialog();
        this.managementService.getAccountAdminNames(this.domainName).done(function (owners) { dialog.setOwners(owners.sort()); });
        this.managementService.getDomainTags(this.domainName).done(function(tags) { dialog.setAvailableTags(tags); });
        return dialog;
    }
});

/** @class */
jscape.domain.EditUrlBrandingController = Class.extend(
    /** @lends {jscape.domain.EditUrlBrandingController.prototype} */
{
    deferred: null,

    start: function (managementService, domainName, theme) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.themeName = theme.name;
        this.themeUri = theme.uri;
        this.deferred = $.Deferred();

        this.managementService.getWebTheme(this.domainName, this.themeName)
                .done($.proxy(function(theme) { this._setupDialog(theme).show(this); }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));

        return this.deferred.promise();
    },

    onSubmit: function (dialog) {
        var theme = this._createWebTheme(dialog);
        dialog.destroy();

        this.managementService.setWebTheme(this.domainName, theme.name, theme)
                .done($.proxy(function() { this.deferred.resolve(theme); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    },

    onCancel: function (dialog) {
        dialog.destroy();
        this.deferred.reject();
        this.deferred = null;
    },

    _createWebTheme: function (dialog) {
        return new jscape.WebTheme(this.themeName,
                                   dialog.getOwner(),
                                   dialog.getLogoData(),
                                   this.themeUri,
                                   dialog.getTags());
    },

    _setupDialog: function (theme) {
        var dialog = new jscape.domain.EditUrlBrandingDialog();
        if (theme) {
            dialog.setName(theme.name);
            dialog.setLogoData(theme.encodedLogo);
            dialog.setUri(theme.uri || "");
        }
        this.managementService.getAccountAdminNames(this.domainName)
                .done(function (owners) {
                          dialog.setOwners(owners.sort());
                          theme && dialog.setOwner(theme.owner);
                      });
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          theme && dialog.setTags(theme.tags);
                      });
        return dialog;
    }
});

/** @class */
jscape.domain.UrlBrandingDialog = Class.extend(
    /** @lends {jscape.domain.UrlBrandingDialog.prototype} */
{
    /** @const */
    DATA_URL: {pattern: /data:image\/.*;base64,(.+)/, template: "data:{0};base64,{1}", placeholder: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"},

    logoData: "",

    /** @constructor */
    initialize: function(dialog) {
        this.dialog = dialog.clone().attr("id", new Date().getTime().toString(36));
        this.dialog.dialog({
            width: 700, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK || "Ok", handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL || "Cancel", handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

        this.fieldset = $("fieldset[name=webthemefields]", this.dialog);

        this.logo = $("div[aria-label=logopreview] img", this.fieldset)
                .attr("id", "logo_" + new Date().getTime().toString(36))
                .on("load error", $.proxy(function () { this.logoFile.filebox("validate"); }, this));
        this.logo.parent()
                .css({width: 500, height: 100, overflow: "auto", border: "1px solid #DEDEDE"})
                .click($.proxy(function () { this._fileInputOf(this.logoFile)[0].click(); }, this));

        this.logoFile = $("input[name=logo]", this.fieldset).filebox({
            required: true,
            accept: "image/*",
            multiple: false,
            validType: "webtheme_logo['#" + this.logo.attr("id") + "']",
            missingMessage: window.R.string.WEB_THEME_ERROR_BAD_LOGO,
            onChange: $.proxy(this._onChange$Logo, this),
            width: "60%"
        });

        this.ownedBy = $("input[name=ownedby]:checkbox", this.fieldset);
        this.ownedBy.change($.proxy(function() { this.owner.combobox(this.ownedBy.is(":checked:not(:disabled)") ? "enable" : "disable");}, this));
        this.owner = $("select[name=owner]", this.fieldset);
        this.owner.combobox({
            required: false,
            editable: true,
            limitToList: true,
            disabled: true,
            width: 120,
            onLoadSuccess: $.proxy(function(data) {
                if (data.length == 0) {
                    this.ownedBy.prop("disabled", true).prop("checked", false).change();
                }
            }, this)
        });

        this.tags = $("select[name=tags]", this.fieldset).tagbox({limitToList: true, hasDownArrow: true, panelHeight: "auto", width: "60%", onLoadSuccess: function() { $(this).tagbox("clear"); }});

        this.uri = $("span[aria-label=themeuri]", this.fieldset);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.fieldset.find("input:first").focus();
    },

    hide: function () {
        if (!this._closed()) {
            this.closing = true;
            this.dialog.dialog("close");
            this.fieldset.form("disableValidation");
            this.closing = false;
        }
    },

    destroy: function() {
        this.dialog.dialog("destroy");
    },

    getName: function() {
        return this.themeName;
    },

    setName: function(value) {
        this.themeName = value;
    },

    getLogoData: function () {
        var dataUrl = this.logo.attr("src");
        return dataUrl && dataUrl != this.DATA_URL.placeholder ? dataUrl.replace(this.DATA_URL.pattern, "$1") : "";
    },

    setLogoData: function (data, type) {
        if (data) {
            this.logo[0].src = this.DATA_URL.pattern.test(data) ? data : this.DATA_URL.template.supplant({0: type || "image/png", 1: data || ""});
            this.logo.data("logo_loaded", true);
        } else {
            this.logo[0].src = this.DATA_URL.placeholder;
            this.logo.data("logo_loaded", false);
        }
    },

    getOwner: function () {
        return this.ownedBy.is(":checked:not(:disabled)") ? this.owner.combobox("getValue") : null;
    },

    setOwner: function (value) {
        this.ownedBy.prop("checked", !!value).change();
        if (value) {
            this.owner.combobox("clear").combobox("select", value);
        }
    },

    setOwners: function (values) {
        this.owner.combobox("loadData", values);
    },

    setAvailableTags: function (values) {
        this.tags.tagbox("loadData", values);
    },

    getTags: function () {
        return this.tags.tagbox("getValues");
    },

    setTags: function (values) {
        this.tags.tagbox("setValues", values);
    },

    setUri: function(value) {
        this.uri.text(value || "");
    },

    _onSubmit: function () {
        if (this.fieldset.form("validate")) {
            this.hide();
            this.listener.onSubmit(this);
        }
    },

    _onCancel: function () {
        this.hide();
        this.listener.onCancel(this);
    },

    _closed: function () {
        return !!this.dialog.dialog("options").closed;
    },

    _onChange$Logo: function() {
        var files = $.grep(this._fileInputOf(this.logoFile)[0].files || [], function(file) { return file && file.type.match("image.*"); });
        if (files.length && window.FileReader) {
            var type = files[0].type;
            var reader = new FileReader();
            reader.onload = $.proxy(function (e) {
                this.setLogoData(e.target.result, type);
                reader.onload = reader.onerror = null;
                type = reader = null;
            }, this);
            reader.onerror = $.proxy(function() {
                this.setLogoData("");
                reader.onload = reader.onerror = null;
                type = reader = null;
            }, this);
            reader.readAsDataURL(files[0]);
        } else {
            this.setLogoData("");
        }
    },

    _fileInputOf: function(filebox) {
        return $("#" + filebox.filebox("options").fileboxId);
    }
});

/** @class */
jscape.domain.AddUrlBrandingDialog = jscape.domain.UrlBrandingDialog.extend(
    /** @lends {jscape.domain.AddUrlBrandingDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-webtheme-add"));

        this.name = $("input[name=name]", this.fieldset).textbox({required: true, validType: ["webtheme_name", "webtheme_unique"], missingMessage: window.R.string.WEB_THEME_ERROR_BAD_NAME, onChange: $.proxy(this._adjustBrandingUri, this), width: "60%"});
    },

    /** @override */
    getName: function() {
        return this.name.textbox("getValue");
    },

    _adjustBrandingUri: function () {
        if (this.name.textbox("isValid")) {
            this.listener.getWebThemeURI(this.getName())
                    .done($.proxy(function(value) { this.setUri(value); }, this))
                    .fail($.proxy(function() { this.setUri(""); }, this));
        } else {
            this.setUri("");
        }
    }
});

/** @class */
jscape.domain.EditUrlBrandingDialog = jscape.domain.UrlBrandingDialog.extend(
    /** @lends {jscape.domain.EditUrlBrandingDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-webtheme-edit"));

        this.title = this.dialog.dialog("header").text() || "";
    },

    /** @override */
    setName: function(value) {
        this._super(value);
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    },

    /** @override */
    setLogoData: function(data) {
        if (data && data.trim().length) {
            this.logoFile.filebox("textbox").validatebox("options").required = false;
        }
        this._super(data);
    }
});

/** @class */
jscape.domain.DeleteUrlBrandingController = Class.extend(
    /** @lends {jscape.domain.DeleteUrlBrandingController.prototype} */
{
    deferred: null,

    start: function(managementService, domainName, themes) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this._confirmDelete(themes)
                .done($.proxy(this._deleteConfirmed, this, themes))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
        return this.deferred.promise();
    },

    _confirmDelete: function(themes) {
        var text = $.map(themes, function(theme) { return theme.name; }).join(", ");
        return jscape.ConfirmDialog.confirm(
                window.R.string.WEB_THEME_CONFIRM_DELETE_TITLE,
                window.R.string.WEB_THEME_CONFIRM_DELETE_MESSAGE.supplant({0: text.escapeXml()}),
                false);
    },

    _deleteConfirmed: function (themes) {
        $.when.apply(jQuery, $.map(themes, $.proxy(function(theme) { return this.managementService.deleteWebTheme(this.domainName, theme.name); }, this)))
                .done($.proxy(function () { this.deferred.resolve(this.themes); this.deferred = null; }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    }
});