/// class PD.Manage.Modules.Resources.ResourceMoveCommand
// using PD.Commands.Command

PD.Manage.Modules.Resources.ResourceMoveCommand =
PD.Commands.Command.extend({

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

    setDefaults: function () {

        this.props("id", "resource/move");
        this.props("enabled", true);
        this.props("label", "Move Resource");

        // State values supplied on execute.
        this.state("destination", null);
        this.state("sourceIds", null);
        this.state("selections", null);

    },

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

        var destination = this.state("destination"),
            selections = this.state("selections"),
            sourceIds = _.map(selections, "id"),
            folders = _.filter(selections, function (item) {
                return item.type === "folder";
            }),
            folderIds = _.map(folders, "id");

        if (this._isValidMove(destination, sourceIds)) {
            this._showTaskDialog(destination.id, sourceIds, folderIds);
        }

    },

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

    _showTaskDialog: function (destinationId, sourceIds, folderIds) {

        var that = this,
            service = new PD.Manage.Services.ResourcesService();

        PD.Shared.Dialogs.TaskStatus.open({
            config: {
                title: "Move Resources"
            },
            showDetail: true,
            enableClose: false,
            taskStart: function (args) {

                service.moveResources(
                    destinationId,
                    sourceIds,
                    function (e) {
                        args.startPolling(e);
                    },
                    function (e) {
                        args.abort(e.responseJSON);
                        e.errorHandled = true;
                    });

            },
            taskSuccess: function (e) {
                e.enableClose(true);
            },
            close: function (e) {

                PD.context
                    .get_default()
                    .get_events()
                    .publish("resource/move", {
                        destinationId: destinationId,
                        folderIds: folderIds
                    });

            }
        });

    },

    _isValidMove: function (destination, sourceIds) {

        var result = true;

        if (_.includes(sourceIds, destination.id)) {

            result = false;

            ProspectDirector.Web.UI.MessageDialog.warn({
                message: "The folder \"" + destination.name + "\" cannot be moved into itself. Please try moving the selections to a different folder location."
            });

        }

        if (destination.type !== "folder") {
            result = false;
        }

        return result;

    }

});