"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const command_base_exec_1 = require("../../command-base-exec");
const config_ui_utils_1 = require("../../uilogic/config-ui-utils");
const _ = require("lodash");
const list_1 = require("./list");
class FilestoreForget extends command_base_exec_1.CommandBaseExec {
    captureArgs() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(FilestoreForget);
            let partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.id)
                partial.id = flags.id;
            if (flags.name)
                partial.name = flags.name;
            // ---------------------------------------------------------------
            // TODO: move everything from here down into the base class
            // ---------------------------------------------------------------
            const interactionMode = (this.pipedInput) ? config_ui_utils_1.InteractionModes.silent : (_b = (_a = undefined !== null && undefined !== void 0 ? undefined : (flags.echo ? config_ui_utils_1.InteractionModes.echo : undefined)) !== null && _a !== void 0 ? _a : (flags["to-script"] ? config_ui_utils_1.InteractionModes.toscript : undefined)) !== null && _b !== void 0 ? _b : (flags.silent ? config_ui_utils_1.InteractionModes.silent : undefined);
            const takeDefaults = flags['take-defaults'];
            return [partial, interactionMode, takeDefaults];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (_.isEmpty(partial.id) && _.isEmpty(partial.name))
                throw new Error("You must provide either an id or a name.");
            // UNCOMMENT THIS WHEN we add enterprise as a reqd property on the FileStoreDef object
            // if (!_.isEmpty(partial.name) && _.isEmpty(partial.enterprise)) throw new Error("Missing enterprise");  
            if (!partial.id) {
                // we've already validated so we can know that canddidate.name is hydrated.
                let found = yield this._codiacApi.FileStoreDef.readMany({ name: { $eq: partial.name } }, { throwNotFound: false });
                if (found.length == 0) {
                    this._ui.userMessage("Item not found; no work to do.");
                    this.exit(0);
                    return;
                }
                else {
                    partial.id = found[0].id;
                }
            }
            let candidate = {
                enterprise: partial.enterprise,
                id: partial.id
            };
            if (partial.name)
                candidate.name = partial.name;
            return candidate;
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let list = yield this._codiacApi.FileStoreDef.readMany({ all: true });
            if (list.length == 0) {
                this._ui.userMessage("There are no filestores captured. No work to do.");
                this.exit(0);
            }
            let selected;
            let found = list.filter(fs => fs.id == partial.id || fs.name == partial.name);
            if (found.length == 1) {
                selected = found[0]; // confirm the match
            }
            else if (list.length == 1) {
                selected = list[0]; // suggest the one and only
            }
            let keep = false;
            if (selected) {
                keep = yield this._ui.promptConfirm("confirmFs", "Forget: ".concat(list_1.FileStoreUiLogic.displayNameFor(selected, this._styler)), false);
            }
            if (!selected || !keep) {
                if (list.length == 1) {
                    this._ui.userMessage("There are no other filestore references.  No work was done.");
                    this.exit(0);
                    return undefined; // this line wont get hit - it's here for ts consistency
                }
                let choices = list.map(x => { return { name: list_1.FileStoreUiLogic.displayNameFor(x, this._styler, false), value: x.id }; });
                partial.id = (yield this._ui.promptSelect("filestore", "Forget: ", choices, false, false));
                selected = list.find(x => x.id == partial.id); // assertion ok
            }
            let candidate = {
                enterprise: partial.enterprise,
                id: selected.id
            };
            candidate.name = selected.name; // this is superfluous, but setting this will yield a --name flag instead of --id in the cmd script.
            return candidate;
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.enterprise)
            cmd.push("--enterprise", candidate.enterprise);
        if (candidate.name) {
            cmd.push("--name", candidate.name);
        }
        else if (candidate.id) {
            cmd.push("--id", candidate.id);
        }
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let result = yield this._codiacApi.FileStoreDef.tryDelete({ id: candidate.id });
            if (result.error)
                throw result.error;
            if (result.success != true) {
                this._ui.userMessage("Item not found; no work to do.");
            }
            else {
                if (result.output) {
                    this._ui.userMessage("Successfully removed filestore reference: ".concat(result.output.name));
                }
            }
        });
    }
}
exports.default = FilestoreForget;
FilestoreForget.description = 'Un-captures an existing filestore instance.  Does NOT delete the physical filestore infrastructure itself; only the reference to it in Codiac.';
FilestoreForget.examples = [
    '<%= config.bin %> <%= command.id %>',
];
FilestoreForget.flags = {
    enterprise: core_1.Flags.string({ char: 'e', description: 'The name of the enterprise in which this filestore reference exists. NOTE: You can leave this blank if there is only one.' }),
    name: core_1.Flags.string({ char: 'n', required: false, exclusive: ["id"], description: 'The name of the filestore reference.  NOTE: This is NOT necessarily the name of the physical filestore entity; just the name given to the reference itself.' }),
    id: core_1.Flags.string({ required: false, exclusive: ["enterprise", "name"], description: "The system id of the filestore reference itself. You can enter this parameter instead of the other filestore descriptors." }),
    // TODO: Move these into the base class
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Non-Interactive mode; executes without any user interaction and fails on any missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Echo interaction mode; renders the equivalent non-interactive cli command for future use before final execution.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Toscript interaction mode; renders the equivalent non-interactive cli command WITHOUT any execution.' }),
    "take-defaults": core_1.Flags.boolean({ exclusive: ["silent"], description: "Setting this to true prevents prompting for confirmation on parameters that were passed in or were automatically set to default values (Irrelevant in --silent mode).  This behavior does NOT apply to scenarios that the command needs to override invalid user input; such cases will always prompt for confirmation.  eg: when no argument was provided for file or type, and only one exists, the system will render the autoselected file unless this flag is set." })
};
FilestoreForget.args = {};
//# sourceMappingURL=forget.js.map