jscape.account = jscape.account || {};

/** @class */
jscape.ContactInfo = Class.extend(
    /** @lends {jscape.ContactInfo.prototype} */
{
    /** @constructor */
    initialize: function(id, name, email, company, owner) {
        this.id = id || undefined;
        this.name = name || "" ;
        this.email = email || "";
        this.company = company || null;
        this.owner = owner || null;
    }
});
jscape.ContactInfo.fromJSON = function(data) {
    return data ? new jscape.ContactInfo(data.id, data.name, data.email, data.company, data.owner) : null;
};

/** @class */
jscape.ContactData = Class.extend(
    /** @lends {jscape.ContactData.prototype} */
{
    /** @constructor */
    initialize: function(name, email, company, isPublic) {
        this.name = name || "";
        this.email = email || "";
        this.company = company || "";
        this.public = !!isPublic;
    }
});
jscape.ContactData.fromJSON = function(data) {
    return data ? new jscape.ContactData(data.name, data.email, data.company, data.public) :  null;
};

/** @class */
jscape.account.ContactsModule = jscape.ApplicationModule.extend(
    /** @lends {jscape.account.ContactsModule.prototype} */
{
    onCreate: function() {
        this._super.apply(this, arguments);

        this.controller = new jscape.account.ContactsController();
    },

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

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

/** @class */
jscape.account.ContactsController = jscape.ui.DatagridController.extend(
    /** @lends {jscape.account.ContactsController.prototype} */
{
    /** @constructor */
    initialize: function() {
        this.view = new jscape.account.ContactsView();

        this.addController = new jscape.account.AddContactController();
        this.editController = new jscape.account.EditContactController();
        this.deleteController = new jscape.account.DeleteContactController();

        this._initValidators();
    },

    start: function() {
        this.view.show(this);
    },

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

    onRefresh: function (params) {
        params = jscape.Page.requestParameters(params);
        return jscape.API.listContacts(params.startIndex, params.count, params.query)
                .then(jscape.Page.datagridFormatter());
    },

    onAddContact: function() {
        this.addController.start()
                .done($.proxy(this._contactAdded, this));
    },

    onEditContact: function(contact) {
        this.editController.start(contact.id)
                .done($.proxy(this._contactEdited, this));
    },

    onDeleteContact: function(contacts) {
        this.deleteController.start(contacts)
                .done($.proxy(this._contactDeleted, this, contacts));
    },

    _contactAdded: function(contact) {
        this._recordAdded(contact);
    },

    _contactEdited: function(contact) {
        this._recordEdited(contact);
    },

    _contactDeleted: function (contacts) {
        this._recordDeleted(contacts);
    },

    _initValidators: function() {
        var v = new jscape.Validator();
        v.nonEmptyRule("contact_name_nonempty", window.R.string.CONTACTS_ERROR_BAD_NAME);
    }
});

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

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

        this.fieldset = $("fieldset[name=contactsfields]", container);

        this.data = $("table[role=grid][aria-label=contacts]", this.fieldset);
        this.data.datagrid({
            fit: true,
            fitColumns: true,
            ctrlSelect: true,
            pagination: true,
            search: true,
            remoteSearch: true,
            sortName: "name",
            idField: "id",
            columns: [[
                {field: "name", title: $("thead th:nth-child(1)", this.data).text(), width: 100, sortable: true},
                {field: "company", title: $("thead th:nth-child(2)", this.data).text(), width: 80, sortable: true, sorter: function(a, b) { return a == b ? 0 : a == null || a < b ? -1 : 1; }},
                {field: "email", title: $("thead th:nth-child(3)", this.data).text(), width: 100, sortable: false},
                {field: "owner", title: $("thead th:nth-child(4)", this.data).text(), width: 80, sortable: true, sorter: function(a, b) { return a == b ? 0 : a == null || a < b ? -1 : 1; }}
            ]],
            onSelect: $.proxy(this._adjustState, this),
            onUnselect: $.proxy(this._adjustState, this),
            onDblClickRow: $.proxy(this._onClick$EditButton, this),
            loader: $.proxy(this._onLoad$Data, this),
            onBeforeLoad: function() { return !initializing; },
            onLoadSuccess: $.proxy(this._adjustState, 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)});

        initializing = false;
    },

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

    show: function(listener) {
        this.listener = listener || jscape.account.ContactsView.LISTENER;
        this._adjustState();
    },

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

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

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

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

    _adjustState: function () {
        this.selection = this.data.datagrid("getSelections");
        this.editButton.linkbutton(this.selection.length == 1 ? "enable" : "disable");
        this.deleteButton.linkbutton(this.selection.length != 0 ? "enable" : "disable");
    }
});
jscape.account.ContactsView.LISTENER = {
    onRefresh: $.noop,
    onAddContact: $.noop,
    onEditContact: $.noop,
    onDeleteContact: $.noop
};

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

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

    onSubmit: function(dialog) {
        var contact = this._createContact(dialog);
        dialog.destroy();

        jscape.API.addContact(contact)
                .done($.proxy(function(contact) { this.deferred.resolve(contact); 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;
    },

    _createContact: function(dialog) {
        return new jscape.ContactData(dialog.getName(),
                                      dialog.getEmail(),
                                      dialog.getCompany(),
                                      dialog.getPublic());
    },

    _setupDialog: function () {
        return new jscape.account.AddContactDialog();
    }
});

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

    start: function(contactId) {
        this.contactId = contactId;
        this.deferred = $.Deferred();
        jscape.API.getContact(this.contactId)
                .done($.proxy(function(data) { this._setupDialog(data).show(this); }, this))
                .fail($.proxy(function() { this.deferred.reject(); this.deferred = null; }, this));
        return this.deferred.promise();
    },

    onSubmit: function(dialog) {
        var contact = this._createContact(dialog);
        dialog.destroy();

        jscape.API.updateContact(this.contactId, contact)
                .done($.proxy(function() { this.deferred.resolve(contact); 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;
    },

    _createContact: function(dialog) {
        return new jscape.ContactData(dialog.getName(),
                                      dialog.getEmail(),
                                      dialog.getCompany(),
                                      dialog.getPublic());
    },

    _setupDialog: function (contact) {
        var dialog = new jscape.account.EditContactDialog();
        dialog.setName(contact.name);
        dialog.setEmail(contact.email);
        dialog.setCompany(contact.company);
        dialog.setPublic(contact.public);
        return dialog;
    }
});

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

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

    _confirmDelete: function(contacts) {
        var text = $.map(contacts || [], function(contact) { return contact.name; }).join(", ");
        return jscape.ConfirmDialog.confirm(
                window.R.string.CONTACTS_CONFIRM_DELETE_TITLE,
                window.R.string.CONTACTS_CONFIRM_DELETE_MESSAGE.supplant({0: text}));
    },

    _deleteConfirmed: function(contacts) {
        $.when.apply(jQuery, $.map(contacts, $.proxy(function(contact) { return jscape.API.deleteContact(contact.id); }, this)))
                .done($.proxy(function () { this.deferred.resolve(contacts); this.deferred = null; }, this))
                .fail($.proxy(function () { this.deferred.reject(); this.deferred = null; }, this));
    }
});

/** @class */
jscape.account.ContactDialog = Class.extend(
    /** @lends {jscape.account.ContactDialog.prototype} */
{
    /** @constructor */
    initialize: function(dialog) {
        this.dialog = dialog.clone().attr("id", "");
        this.dialog.dialog({
            width: 530, height: "auto",
            modal: true, resizable: false, closable: true, closed: true,
            buttons: [
                {text: window.R.string.DIALOG_BUTTON_OK, handler: $.proxy(this._onSubmit, this)},
                {text: window.R.string.DIALOG_BUTTON_CANCEL, handler: $.proxy(this._onCancel, this)}
            ],
            onClose: $.proxy(function () {if (!this.closing) { this._onCancel(); }}, this)
        }).show();

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

        this.name = $("[name=name]", this.fieldset).textbox({required: true, validType: "contact_name_nonempty", missingMessage: window.R.string.CONTACTS_ERROR_BAD_NAME, width: "60%"});
        this.email = $("[name=email]", this.fieldset).textbox({required: true, validType: "multi_value['email',',']", missingMessage: window.R.string.CONTACTS_ERROR_BAD_EMAIL, invalidMessage: window.R.string.CONTACTS_ERROR_BAD_EMAIL, width: "60%"});
        this.company = $("[name=company]", this.fieldset).textbox({width: "60%"});
        this.public = $("[name=public]:checkbox", this.fieldset);
    },

    show: function (listener) {
        this.listener = listener;
        this.dialog.dialog("center").dialog("open");
        this.fieldset.form("validate");
        this.name.textbox("textbox").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.name.textbox("getValue");
    },

    setName: function(value) {
        this.name.textbox("setValue", value);
    },

    getEmail: function() {
        return this.email.textbox("getValue");
    },

    setEmail: function(value) {
        this.email.textbox("setValue", value);
    },

    getCompany: function() {
        return this.company.textbox("getValue");
    },

    setCompany: function(value) {
        this.company.textbox("setValue", value);
    },

    getPublic: function() {
        return this.public.is(":checked");
    },

    setPublic: function(value) {
        this.public.prop("checked", !!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;
    }
});

/** @class */
jscape.account.AddContactDialog = jscape.account.ContactDialog.extend(
    /** @lends {jscape.account.AddContactDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-contacts-add"));
    }
});

/** @class */
jscape.account.EditContactDialog = jscape.account.ContactDialog.extend(
    /** @lends {jscape.account.EditContactDialog.prototype} */
{
    /** @constructor */
    initialize: function() {
        this._super($("#d-contacts-edit"));

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

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