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

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

    onSubmit: function(dialog) {
        var provider = this._createKeyProvider(dialog);
        dialog.destroy();
        this.deferred.resolve(provider);
    },

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

    onSelectKeyFile: function(dialog) {
        new SelectPathController($.proxy(this.managementService.listKeystorePath, this.managementService),
                                 $.proxy(this.managementService.createKeystoreDir, this.managementService))
                .selectFile()
                .done(function(entry) { dialog.setKeyFile(entry.path); });
    },

    _setupDialog: function(keyProvider) {
        var dialog = new jscape.domain.ClientKeyDialog();
        if (keyProvider instanceof jscape.FileKeyProvider) {
            dialog.setUseFile(keyProvider.file, keyProvider.filePassword);
        } else {
            dialog.setUseNone();
        }
        this.managementService.getServerKeys()
                .then(function(keys) { return $.map(keys, function(key) { return key.name; })})
                .done(function(serverKeys) {
                    dialog.setServerKeys(serverKeys);
                    if (keyProvider instanceof jscape.ServerKeyProvider) {
                        dialog.setServerKey(keyProvider.keyAlias);
                    }
                });
        return dialog;
    },

    _createKeyProvider: function(dialog) {
        if (dialog.isUseServerKey()) {
            return new jscape.ServerKeyProvider(dialog.getServerKey());
        } else if (dialog.isUseFile()) {
            return new jscape.FileKeyProvider(dialog.getKeyFile(), dialog.getKeyFilePassword());
        }
        return null;
    }
});

/** @class */
jscape.domain.ClientKeyDialog = Class.extend(
    /** @lends {jscape.domain.ClientKeyDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.dialog = $("#d-clientkeys").clone().attr("id", "");
        this.dialog.dialog({
            width: 580, 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=clientkeyfields]", this.dialog);
        this.types = $("input[name=type]:radio", this.fieldset);
        this.typeNone = this.types.filter("[value=none]");
        this.typeServerKey = this.types.filter("[value=serverkey]");
        this.typeKeyFile = this.types.filter("[value=keyfile]");
        this.types.change($.proxy(this._adjustFieldState, this));

        this.serverKey = $("select[name=serverkey]", this.fieldset);
        this.serverKey.combobox({required: true, editable: false, disabled: true, width: 170, panelHeight: "auto", onLoadSuccess: $.proxy(function() {
            var data = this.serverKey.combobox("getData");
            if (data.length != 0) {
                this.serverKey.combobox("setValue", data[0].value);
            } else {
                this.serverKey.combobox("disable");
            }
            this.typeServerKey.prop("disabled", data.length == 0);
        }, this)});

        this.keyFile = $("input[name=keyfile]", this.fieldset).textbox({required: true, missingMessage: window.R.string.DOMAIN_ERROR_BAD_KEY_FILE, width: "50%"});
        this.keyFilePassword = $("input[name=keyfilepwd]", this.fieldset).textbox({type: "password", width: "50%"});
        this.browseKeyFile = $("a[role=button][name=browsekeyfile]", this.fieldset).linkbutton({disabled: true, onClick: $.proxy(this._onClick$BrowseKeyFile, this)});
    },

    isUseNone: function() {
        return this.typeNone.is(":checked");
    },

    setUseNone: function() {
        this.typeNone.prop("checked", true).change();
    },

    isUseServerKey: function() {
        return this.typeServerKey.is(":checked");
    },

    getServerKey: function() {
        return this.isUseServerKey() ? this.serverKey.combobox("getValue") : null;
    },

    setServerKey: function(value) {
        this.serverKey.combobox("select", value);
        this.typeServerKey.prop("checked", value != null).change();
    },

    setServerKeys: function(values) {
        this.serverKey.combobox("loadData", values);
    },

    isUseFile: function() {
        return this.typeKeyFile.is(":checked");
    },

    setUseFile: function(file, filepwd) {
        this.typeKeyFile.prop("checked", true).change();
        this.keyFile.textbox("setValue", file);
        this.keyFilePassword.textbox("setValue", filepwd);
    },

    getKeyFile: function() {
        return this.keyFile.textbox("getValue");
    },

    setKeyFile: function(value) {
        this.keyFile.textbox("setValue", value);
    },

    getKeyFilePassword: function() {
        return this.keyFilePassword.textbox("getValue");
    },

    show: function (listener) {
        this.listener = listener || jscape.domain.ClientKeyDialog.LISTENER;
        this.dialog.dialog("center");
        this.dialog.dialog("open");

        this.fieldset.form("validate");
        this.dialog.find(".dialog-button input:first").focus();
        this._adjustFieldState();
    },

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

    _onClick$BrowseKeyFile: function() {
        this.listener.onSelectKeyFile(this);
    },

    _adjustFieldState: function() {
        this.serverKey.combobox(this.isUseServerKey() ? "enable" : "disable");
        var useKeyFile = this.isUseFile();
        $.each([this.keyFile, this.keyFilePassword], function(_, input) {
            input.textbox(useKeyFile ? "enable" : "disable").textbox(useKeyFile ? "enableValidation" : "disableValidation");
        });
        this.browseKeyFile.linkbutton(useKeyFile ? "enable" : "disable");
    },

    _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.ClientKeyDialog.LISTENER = {
    onSelectKeyFile: $.noop
};