/// class PD.Manage.Modules.UserMembershipAddCommand

PD.Manage.Modules.UserMembershipAddCommand =
PD.Commands.Command.extend({

    //===================================
    // PUBLIC METHODS
    //===================================

    setDefaults: function () {
        this.props("id", "user/memberships-add");
        this.props("enabled", true);
        this.props("icon", PD.Path.to16x16("plus.png"));
        this.props("label", "Add Membership");
        this.props("tooltip", "Add Membership");
        this.state("membership", null);
    },

    setState: function (state) {
        this._super(state);
        this.props("enabled", this._isEnabled());
    },

    execute: function (e) {
        this._super(e);

        this._showDialog(function (e) {

            var selections = e;
            var memberships = [];
            var membership = this.state("membership");

            _.each(selections, function (member) {
                memberships[memberships.length] = member.id;
                membership.remove = _.without(membership.remove, member.id);
                if (!_.includes(membership.add, member.id)) {
                    membership.add[membership.add.length] = member.id;
                }
            });

            PD.context.get_default().get_events().publish("user/memberships-added", {
                memberships: memberships
            });

        });

    },

    //===================================
    // PRIVATE METHODS
    //===================================

    _isEnabled: function () {
        var membership = this.state("membership");
        return membership != null
            && _.isArray(membership.add)
            && _.isArray(membership.remove);
    },

    _showDialog: function (callback) {

        callback = _.bind(callback, this);

        PDJS.Shared.Security.IdentityBrowserDialog.open({
            title: "Find Groups",
            filters: [
                PDJS.Core.Views.IdentityFilter.groupsOnly(),
                PDJS.Core.Views.IdentityFilter.excludeEveryone()
            ],
            callbacks: {
                ok: function (sender, e) {
                    callback(e);
                }
            }
        });

    }

});