"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const codiac_domain_1 = require("@codiac.io/codiac-domain");
const command_base_enterprise_1 = require("../../../command-base-enterprise");
const ops_1 = require("../../../ops");
class NocClusterDestroy extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a;
                try {
                    this.bootstrap();
                    const { args, flags } = yield this.parse(NocClusterDestroy);
                    (_a = this._relayContainer) === null || _a === void 0 ? void 0 : _a.ready$.subscribe((ready) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                        var _b, _c, _d;
                        try {
                            if (flags.silent)
                                this.__ui = new ops_1.ThrowingUserInputProvider(this.logger);
                            this._userCntx = yield this.establishTenantContext(this._userCntx);
                            let deleteIdentity = flags.deleteIdentity;
                            // let clusterName: string | undefined;
                            // if (!flags.name) {
                            //   let readResult = await this._codiacApi.ClusterDef.tryReadMany({ privateOwner: this._userCntx?.currentTenantCode! }, { projection: { pathsIncluded: ["id", "name", "locationName", "privateOwner"], pathsExcluded: [] } });
                            //   if (readResult.error) {
                            //     clusterName = <string>(await this._ui.prompt("clusterName", "Enter name of the cluster to destroy:", true));
                            //     deleteIdentity = await this._ui.promptConfirm("deleteIdentity", "Delete the cluster identity also?", false);
                            //   } else if (readResult.success && readResult.output && readResult.output.length > 0) {
                            //     let clusterList = readResult.output;
                            //     if (flags.partials !== true) {
                            //       clusterList = clusterList.filter(c => c.instance != undefined)
                            //     }
                            //     let instances = clusterList.map(c => { return { name: `${c.name} [${c.locationName}]${c.privateOwner ? this._styler.dim(" Owner: [" + c.privateOwner + "]") : ""}`, value: c.name }; });
                            //     clusterName = (await this._ui.promptSelect("clusterName", "Select the cluster to destroy:", instances))!;
                            //     deleteIdentity = await this._ui.promptConfirm("deleteIdentity", "Delete the cluster identity also?", false);
                            //   } else {
                            //     this._ui.userMessage("No clusters exist to destroy");
                            //   }
                            // } else {
                            //   clusterName = flags.name;  // TODO:  Validate this and prompt for selection if not found.
                            // }
                            let cluster;
                            let crit = { privateOwner: (_b = this._userCntx) === null || _b === void 0 ? void 0 : _b.currentTenantCode };
                            let readResult = yield this._codiacApi.ClusterDef.tryReadMany(crit, { projection: { pathsIncluded: ["id", "name", "provider", "providerSubscription", "locationName", "privateOwner", "instance"], pathsExcluded: [] } });
                            let clusterDefs = (_c = readResult.output) !== null && _c !== void 0 ? _c : []; // we can only deinit clusters that have an instance
                            if (flags.partials !== true) {
                                clusterDefs = clusterDefs.filter(c => c.instance != undefined);
                            }
                            let provider = (flags.provider) ? codiac_domain_1.CloudProviderEnum[flags.provider] : undefined;
                            if (provider && Object.keys(codiac_domain_1.CloudProviderEnum).indexOf(provider) >= 0) {
                                clusterDefs = clusterDefs.filter(c => c.provider == provider);
                            }
                            let confirm = false;
                            if (readResult.error === undefined && clusterDefs.length === 0) {
                                this._ui.userMessage("No clusters exist with instances to destroy");
                            }
                            else if (flags.silent) {
                                const subx = (_d = clusterDefs.find(c => c.name == flags.name && c.provider == provider)) === null || _d === void 0 ? void 0 : _d.providerSubscription;
                                cluster = { name: flags.name, provider: (provider), providerSubscription: subx };
                            }
                            else {
                                let candidate = {};
                                if (flags.name)
                                    candidate.name = flags.name;
                                do {
                                    if (readResult.error) {
                                        // if there is a problem with the cluster record, it may prevent a good read, 
                                        // so we're going to allow the user to invoke the operation nonetheless.
                                        let allPvds = this.cspUiFactory.getAllProviders(this.ioc);
                                        const csp = yield this.cspContextualizer.promptForCloudProvider(allPvds, undefined);
                                        const name = (yield this._ui.prompt("clusterName", "Enter name of the cluster to destroy:", true));
                                        const subx = (yield this._ui.prompt("clusterSubx", (csp == codiac_domain_1.CloudProviderEnum.aws ? "AccountId" : "SubscriptionId").concat(" of the cluster to deinitialize:"), true));
                                        deleteIdentity = yield this._ui.promptConfirm("deleteIdentity", "Delete the cluster identity also?", false);
                                        cluster = { name: name, provider: csp, providerSubscription: subx };
                                    }
                                    else { // if (readResult.success && readResult.output && readResult.output.length > 0) {
                                        let found = (candidate.name) ? clusterDefs.find(c => c.name === candidate.name) : undefined;
                                        if (found) {
                                            cluster = found;
                                        }
                                        else {
                                            let choices = clusterDefs
                                                .map(c => { return { name: this.describe(c), value: c.name }; });
                                            const name = (yield this._ui.promptSelect("clusterName", "Select the cluster to destroy:", choices));
                                            let def = clusterDefs.find(c => c.name === name);
                                            cluster = { name: name, provider: def.provider, providerSubscription: def.providerSubscription };
                                        }
                                    }
                                    let also = (deleteIdentity == true) ? " and its identity" : "";
                                    confirm = yield this._ui.promptConfirm("confirmDestroy", `Destroy the physical cluster instance: ${this._styler.hilite(this.describe(cluster))}${also} ? `, false);
                                    if (!confirm)
                                        candidate = {}; // if cluster was set as a cmd flag, but they denied the confirm, this allows selecting a different one.
                                } while (confirm !== true);
                            }
                            if (cluster) {
                                if (confirm == true || flags.silent) {
                                    if (!flags.silent) {
                                        yield this.cspContextualizer.promptForCloudProviderCreds(this.ioc, cluster.provider, undefined, undefined, undefined, cluster.providerSubscription);
                                    }
                                    this._ui.startSpinner(`Destroying physical cluster instance: ${this._styler.hilite(cluster.name)}...`);
                                    let result = yield this.genRelayClient.Call.postExecuteDeleteClusterInstance({ name: cluster.name, deleteIdentity: deleteIdentity });
                                    this._ui.stopSpinner(result.success ? "SUCCESS" : "FAILED");
                                    let msg = `Cluster destroy ${result.success ? this._styler.colorGood("SUCCESS") : this._styler.colorCritical("FAILED")}: ${result.message || ""}`;
                                    this.logger.debug(msg, result);
                                    this._ui.userMessage(msg);
                                }
                                else {
                                    this._ui.userMessage("Operation cancelled.  No work was done.");
                                }
                            }
                            resolve();
                        }
                        catch (err) {
                            reject(err);
                        }
                    }));
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Renders a user-friendly cluster description. */
    describe(cluster) {
        return `${cluster.name} ${this._styler.dim("(" + cluster.provider + (cluster.locationName ? ", " + cluster.locationName : "") + ")")}`;
    }
}
exports.default = NocClusterDestroy;
NocClusterDestroy.description = 'Kills the physical cluster, but not the Codiac cluster definition record';
NocClusterDestroy.aliases = ["cluster:destroy"];
NocClusterDestroy.dependsOn = ["name"];
NocClusterDestroy.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    name: core_1.Flags.string({ char: 'n', required: false, description: 'Name of the cluster.' }),
    partials: core_1.Flags.boolean({ char: 'p', description: "Include clusters that were never fully created." }),
    deleteIdentity: core_1.Flags.boolean({ char: 'i', required: false, default: false, description: '(optional: defaults to false) Ensures that identity security account for the cluster shall also be deleted after the cluster itself is destroyed.' }),
    provider: core_1.Flags.string({ char: 'p', options: Object.keys(codiac_domain_1.CloudProviderEnum), required: false, description: 'Code for the cloud service provider.' }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: NocClusterDestroy.dependsOn, required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values. Required: ${NocClusterDestroy.dependsOn}` })
};
NocClusterDestroy.args = {
    name: core_1.Args.string({ description: 'Proposed name of the cluster' })
};
//# sourceMappingURL=destroy.js.map