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

/** @class */
jscape.DropZoneDescriptor = Class.extend(
    /** @lends {jscape.DropZoneDescriptor.prototype} */
{
    /** @constructor */
    initialize: function(a, b, c, d, e, f, g, h, i) {
        this.name = a || "";
        this.account = b || "";
        this.path = c || "";
        this.createDirectoryIfNotExists = d != undefined ? !!d : true;
        this.overwriteFileIfExists = e || false;
        this.theme = f || null;
        this.owner = g || null;
        this.uri = h || "";
        this.tags = i || [];
    }
});
jscape.DropZoneDescriptor.fromJSON = function(data) {
    return data ? new jscape.DropZoneDescriptor(data.name, data.account, data.path, data.createDirectoryIfNotExists, data.overwriteFileIfExists, data.theme, data.owner, data.uri, data.tags) : null;
};

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

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

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

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

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

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

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

        this.addController = new jscape.domain.AddDropZoneController();
        this.editController = new jscape.domain.EditDropZoneController();
        this.deleteController = new jscape.domain.DeleteDropZoneController();
        this.purgeController = new jscape.domain.PurgeDropZoneController();
    },

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

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

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

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

    onEditZone: function(dropzone) {
        var index = $.inArray(dropzone, this.view.getDropZones());
        if (index != -1) {
            this.editController.start(this.managementService, this.domainName, dropzone)
                    .done($.proxy(this._dropZoneEdited, this, index));
        }
    },

    onDeleteZone: function(dropzones) {
        this.deleteController.start(this.managementService, this.domainName, dropzones)
                .done($.proxy(this._dropZoneDeleted, this, dropzones));
    },

    onPurgeZone: function(dropzone) {
        this.purgeController.start(this.managementService, this.domainName, dropzone);
    },

    _dropZoneAdded: function(dropzone) {
        this._recordAdded(dropzone);
    },

    _dropZoneEdited: function(index, dropzone) {
        this._recordEdited(dropzone);
    },

    _dropZoneDeleted: function(dropzones) {
        this._recordDeleted(dropzones);
    },

    _initValidators: function () {
        var v = new jscape.Validator();
        v.rule("dropzone_name", $.proxy(this._dropZoneNameValid, this), window.R.string.DROP_ZONE_ERROR_BAD_NAME);
        v.rule("dropzone_unique", $.proxy(this._dropZoneNotExists, this), window.R.string.DROP_ZONE_ERROR_ALREADY_EXIST);
        v.nonEmptyRule("dropzone_path_nonempty", window.R.string.DROP_ZONE_ERROR_BAD_PATH);
    },

    _dropZoneNameValid: function(name) {
        return /^\w+$/g.test(name);
    },

    _dropZoneNotExists: function(name) {
        var values = $.map(this.view.getDropZones(), function(dropzone) { return dropzone.name; });
        return $.inArray(name, values) == -1;
    }
});

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

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

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

        this.data = $("table[role=grid][aria-label=dropzones]", 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: 50},
                {field: "account", title: $("thead th:nth-child(2)", this.data).text(), sortable: true, width: 50},
                {field: "path", title: $("thead th:nth-child(3)", this.data).text(), width: 90},
                {field: "uri", title: $("thead th:nth-child(4)", this.data).text(), width: 90, searchable: false},
                {field: "owner", title: $("thead th:nth-child(5)", this.data).text(), sortable: true, width: 50, sorter: function(a, b) { return a == b ? 0 : a == null || a < b ? -1 : 1; }},
                {field: "theme", title: $("thead th:nth-child(6)", this.data).text(), width: 50},
                {field: "tags", title: $("thead th:nth-child(7)", 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.purgeButton = $("a[role=button][name=purge]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$PurgeButton, this)});

        initializing = false;
    },

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

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

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

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

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

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

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

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

    _adjustButtonsState: function () {
        var singleSelection = this.selection.length == 1;
        this.editButton.linkbutton(singleSelection ? "enable" : "disable");
        this.purgeButton.linkbutton(singleSelection ? "enable" : "disable");
        this.deleteButton.linkbutton(this.selection.length != 0 ? "enable" : "disable");
    }
});
jscape.domain.DropZonesView.LISTENER = {
    onRefresh: $.noop,
    onAddZone: $.noop,
    onEditZone: $.noop,
    onDeleteZone: $.noop,
    onPurgeZone: $.noop
};

/** @class */
jscape.domain.AddDropZoneController = Class.extend(
    /** @lends {jscape.domain.AddDropZoneController.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 descriptor = this._createDescriptor(dialog);
        dialog.destroy();

        this.managementService.addDropZone(this.domainName, descriptor)
                .done($.proxy(function(descriptor) { this.deferred.resolve(descriptor); 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;
    },

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

    _setupDialog: function() {
        var dialog = new jscape.domain.AddDropZoneDialog();
        dialog.setCreatePathIfNotExists(true);
        dialog.setOverwriteFileIfExists(true);

        this.managementService.getAccountNames(this.domainName).done(function(users) { dialog.setUsers(users.sort()); });
        this.managementService.getAccountAdminNames(this.domainName).done(function(owners) { dialog.setOwners(owners.sort()); });
        this.managementService.getWebThemeNames(this.domainName).done(function(themes) { dialog.setWebThemes(themes.sort()); });
        this.managementService.getDomainTags(this.domainName).done(function(tags) { dialog.setAvailableTags(tags); });

        return dialog;
    },

    _createDescriptor: function(dialog) {
        return new jscape.DropZoneDescriptor(dialog.getName(),
                                             dialog.getUser(),
                                             dialog.getPath(),
                                             dialog.getCreatePathIfNotExists(),
                                             dialog.getOverwriteFileIfExists(),
                                             dialog.getWebTheme(),
                                             dialog.getOwner(),
                                             null,
                                             dialog.getTags());
    }
});

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

    start: function (managementService, domainName, descriptor) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.zoneName = descriptor.name;
        this.deferred = $.Deferred();

        this.managementService.getDropZone(this.domainName, descriptor.name)
                .done($.proxy(function(descriptor) { this._setupDialog(descriptor).show(this); }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));

        return this.deferred.promise();
    },

    onSubmit: function (dialog) {
        var descriptor = this._createDescriptor(dialog);
        dialog.destroy();

        this.managementService.setDropZone(this.domainName, descriptor.name, descriptor)
                .done($.proxy(function(descriptor) { this.deferred.resolve(descriptor); 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;
    },

    _setupDialog: function(descriptor) {
        var dialog = new jscape.domain.EditDropZoneDialog();
        if (descriptor) {
            dialog.setName(descriptor.name);
            dialog.setPath(descriptor.path);
            dialog.setCreatePathIfNotExists(descriptor.createDirectoryIfNotExists);
            dialog.setOverwriteFileIfExists(descriptor.overwriteFileIfExists);
            dialog.setUri(descriptor.uri);
        }
        this.managementService.getAccountNames(this.domainName)
                .done(function (users) {
                          dialog.setUsers(users.sort());
                          descriptor && dialog.setUser(descriptor.account);
                      });
        this.managementService.getAccountAdminNames(this.domainName)
                .done(function (owners) {
                          dialog.setOwners(owners.sort());
                          descriptor && dialog.setOwner(descriptor.owner);
                      });
        this.managementService.getWebThemeNames(this.domainName)
                .done(function (themes) {
                          dialog.setWebThemes(themes.sort());
                          descriptor && dialog.setWebTheme(descriptor.theme);
                      });
        this.managementService.getDomainTags(this.domainName)
                .done(function (tags) {
                          dialog.setAvailableTags(tags);
                          descriptor && dialog.setTags(descriptor.tags);
                      });
        return dialog;
    },

    _createDescriptor: function(dialog) {
        return new jscape.DropZoneDescriptor(this.zoneName,
                                             dialog.getUser(),
                                             dialog.getPath(),
                                             dialog.getCreatePathIfNotExists(),
                                             dialog.getOverwriteFileIfExists(),
                                             dialog.getWebTheme(),
                                             dialog.getOwner(),
                                             null,
                                             dialog.getTags());
    }
});

/** @class */
jscape.domain.DropZoneDialog = Class.extend(
    /** @lends {jscape.domain.DropZoneDialog.prototype} */
{
    /** @constructor */
    initialize: function(dialog) {
        this.dialog = dialog.clone().attr("id", new Date().getTime().toString(36));
        this.dialog.dialog({
            width: 530, 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=dropzonefields]", this.dialog);

        this.path = $("input[name=path]", this.fieldset).textbox({required: true, validType: "dropzone_path_nonempty", missingMessage: window.R.string.DROP_ZONE_ERROR_BAD_PATH, width: "60%"});
        this.user = $("select[name=account]", this.fieldset).combobox({required: true, editable: true, limitToList: true, missingMessage: window.R.string.DROP_ZONE_ERROR_BAD_ACCOUNT, width: 120});

        this.ownedBy = $("input[name=ownedby]:checkbox", this.fieldset);
        this.ownedBy.change($.proxy(function() {
            this.owner.combobox(this.ownedBy.is(":checked") ? "enable" : "disable");
        }, this));
        this.owner = $("select[name=owner]", this.fieldset);
        this.owner.combobox({
            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.brandedBy = $("input[name=brandedby]:checkbox", this.fieldset);
        this.brandedBy.change($.proxy(function() {
            this.theme.combobox(this.brandedBy.is(":checked") ? "enable" : "disable");
        }, this));
        this.theme = $("select[name=webtheme]", this.fieldset);
        this.theme.combobox({
            editable: true,
            limitToList: true,
            disabled: true,
            width: 120,
            panelHeight: "auto",
            onLoadSuccess: $.proxy(function(data) {
                if (data.length == 0) {
                    this.brandedBy.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.createPath = $("input[name=createpath]:checkbox", this.fieldset);
        this.overwrite = $("input[name=overwrite]:checkbox", this.fieldset);
        this.uri = $("span[aria-label=zoneuri]", this.fieldset);
    },

    getPath: function() {
        return this.path.textbox("getValue");
    },

    setPath: function(value) {
        this.path.textbox("setValue", value);
    },

    getUser: function() {
        return this.user.combobox("getValue");
    },

    setUser: function(value) {
        this.user.combobox("select", value);
    },

    setUsers: function(values) {
        this.user.combobox("loadData", values);
    },

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

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

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

    getWebTheme: function () {
        return this.brandedBy.is(":checked:not(:disabled)") ? this.theme.combobox("getValue") : null;
    },

    setWebTheme: function (value) {
        this.brandedBy.prop("checked", value != null).change();
        if (value != null) {
            this.theme.combobox("select", value);
        }
    },

    setWebThemes: function (values) {
        this.theme.combobox("loadData", values.sort());
    },

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

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

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

    getCreatePathIfNotExists: function() {
        return this.createPath.is(":checked");
    },

    setCreatePathIfNotExists: function(value) {
        this.createPath.prop("checked", !!value);
    },

    getOverwriteFileIfExists: function() {
        return this.overwrite.is(":checked");
    },

    setOverwriteFileIfExists: function(value) {
        this.overwrite.prop("checked", !!value);
    },

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

    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");
    },

    _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;
    }
});
jscape.domain.DropZoneDialog.LISTENER = {
    onSubmit: $.noop,
    onCancel: $.noop
};

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

        this.name = $("input[name=name]", this.fieldset).textbox({required: true, validType: ["dropzone_name", "dropzone_unique"], missingMessage: window.R.string.DROP_ZONE_ERROR_BAD_NAME, onChange: $.proxy(this._onChange$Name, this), width: "60%"})
    },

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

    /** @override */
    show: function (listener) {
        this._super(listener || jscape.domain.AddDropZoneDialog.LISTENER);
    },

    _onChange$Name: function() {
        if (this.name.textbox("isValid")) {
            this.listener.dropZoneUriFor(this.name.textbox("getValue"))
                    .done($.proxy(function (value) { this.setUri(value); }, this))
                    .fail($.proxy(function () { this.setUri(""); }, this))
        } else {
            this.setUri("");
        }
    }
});
jscape.domain.AddDropZoneDialog.LISTENER = $.extend({
    dropZoneUriFor: $.noop
}, jscape.domain.DropZoneDialog.LISTENER);


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

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

    setName: function(value) {
        this.dialog.dialog("setTitle", this.title.supplant({0: value}));
    }
});


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

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

    _confirmDelete: function(items) {
        var text = $.map(items, function(dropzone) { return dropzone.name; }).join(", ");
        return jscape.ConfirmDialog.confirm(
                window.R.string.DROP_ZONE_CONFIRM_DELETE_TITLE,
                window.R.string.DROP_ZONE_CONFIRM_DELETE_MESSAGE.supplant({0: text.escapeXml()}),
                false);
    },

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

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

    start: function(managementService, domainName, descriptor) {
        this.managementService = managementService;
        this.domainName = domainName;
        this.deferred = $.Deferred();
        this._confirmPurge(descriptor.name)
                .done($.proxy(this._purgeConfirmed, this, descriptor.name))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
        return this.deferred.promise();
    },

    _confirmPurge: function(zoneName) {
        return jscape.ConfirmDialog.confirm(
                window.R.string.DROP_ZONE_CONFIRM_PURGE_TITLE,
                window.R.string.DROP_ZONE_CONFIRM_PURGE_MESSAGE.supplant({0: zoneName}));
    },

    _purgeConfirmed: function (zoneName) {
        this.managementService.purgeDropZone(this.domainName, zoneName)
                .done($.proxy(function() { this.deferred.resolve(zoneName); this.deferred = null; } , this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
    }
});