"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const command_base_exec_1 = require("../../command-base-exec");
const list_1 = require("../filestore/list");
const list_2 = require("./list");
class PvcDelete extends command_base_exec_1.CommandBaseExec {
    captureArgs() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(PvcDelete);
            const partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.name)
                partial.name = flags.name;
            if (flags.id)
                partial.id = flags.id;
            const takeDefaults = (_a = flags['take-defaults']) !== null && _a !== void 0 ? _a : false;
            return [partial, 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("Provide either --name or --id.");
            }
            if (!partial.id) {
                const found = yield this._codiacApi.FileStoreDef.readMany({ name: { $eq: partial.name } }, { throwNotFound: false });
                const pvcMatches = found.filter(list_2.isPvcFileStore);
                if (pvcMatches.length === 0) {
                    this._ui.userMessage(`No PVC filestore named [${partial.name}] was found; no work to do.`);
                    this.exit(0);
                    return;
                }
                if (pvcMatches.length > 1) {
                    throw new Error(`Multiple PVC filestores match name [${partial.name}]. Resolve with --id.`);
                }
                partial.id = pvcMatches[0].id;
            }
            const 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* () {
            const all = yield this._codiacApi.FileStoreDef.readMany({ all: true });
            const pvcList = all.filter(list_2.isPvcFileStore);
            if (pvcList.length === 0) {
                this._ui.userMessage("There are no PVC filestores defined. No work to do.");
                this.exit(0);
                return undefined;
            }
            let selected;
            const matched = pvcList.filter(fs => fs.id === partial.id || fs.name === partial.name);
            if (matched.length === 1) {
                selected = matched[0];
            }
            else if (pvcList.length === 1) {
                selected = pvcList[0];
            }
            let keep = false;
            if (selected) {
                keep = yield this._ui.promptConfirm("confirmPvc", "Delete: ".concat(list_1.FileStoreUiLogic.displayNameFor(selected, this._styler)), false);
            }
            if (!selected || !keep) {
                if (pvcList.length === 1) {
                    this._ui.userMessage("There are no other PVC filestores. No work was done.");
                    this.exit(0);
                    return undefined;
                }
                const choices = pvcList.map(x => ({ name: list_1.FileStoreUiLogic.displayNameFor(x, this._styler, false), value: x.id }));
                partial.id = (yield this._ui.promptSelect("pvc", "Delete: ", choices, false, false));
                selected = pvcList.find(x => x.id === partial.id);
            }
            const candidate = {
                enterprise: partial.enterprise,
                id: selected.id,
                name: selected.name,
            };
            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* () {
            const 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.");
                return;
            }
            if (result.output) {
                this._ui.userMessage(`${this._styler.colorGood("SUCCESS")}: removed PVC filestore [${result.output.name}].`);
            }
        });
    }
}
exports.default = PvcDelete;
PvcDelete.description = 'Deletes a PersistentVolumeClaim-backed filestore definition. Removes the FileStoreDef record in Codiac; physical PVCs in cabinets are reaped on the next deploy.';
PvcDelete.aliases = ['pvc:delete'];
PvcDelete.examples = [
    {
        description: 'Delete by name (interactive enterprise resolution).',
        command: '<%= config.bin %> <%= command.id %> --name shared-files',
    },
    {
        description: 'Delete by name in a specific enterprise.',
        command: '<%= config.bin %> <%= command.id %> -e myEnt --name shared-files --silent',
    },
    {
        description: 'Delete by id (when name is ambiguous).',
        command: '<%= config.bin %> <%= command.id %> --id <fileStoreDefId> --silent',
    },
];
PvcDelete.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    enterprise: core_1.Flags.string({ char: 'e', description: 'Code name identifying the enterprise that owns this filestore (optional if there is only one).' }),
    name: core_1.Flags.string({ char: 'n', required: false, exclusive: ["id"], description: 'Name of the PVC filestore to delete.' }),
    id: core_1.Flags.string({ required: false, exclusive: ["name"], description: 'System id of the FileStoreDef record. Use this when --name is ambiguous.' }),
    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)." }),
};
//# sourceMappingURL=delete.js.map