"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const contracts_1 = require("../../../apis/codiac-api/contracts");
const ops_1 = require("../../../ops");
const command_base_enterprise_1 = require("../../../command-base-enterprise");
const type_safety_utils_1 = require("../../../uilogic/type-safety-utils");
class NocClusterDeinit 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(NocClusterDeinit);
                    (_a = this._relayContainer) === null || _a === void 0 ? void 0 : _a.ready$.subscribe(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
                        var _b, _c;
                        try {
                            if (flags.silent)
                                this.__ui = new ops_1.ThrowingUserInputProvider(this.logger);
                            this._userCntx = yield this.establishTenantContext(this._userCntx);
                            // Ensure that the type alias matches the projection...
                            let projection = { pathsIncluded: ["id", "name", "provider", "providerSubscription", "locationName", "privateOwner", "instance"], pathsExcluded: [] };
                            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: projection });
                            let clusterDefs = readResult.output ? readResult.output.map(c => c).filter(c => c.instance != undefined) : []; // we can only deinit clusters that have an instance
                            let provider = (flags.provider) ? type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, flags.provider) : undefined;
                            if (type_safety_utils_1.TypeSafetyUtils.isEnum(contracts_1.CloudProviderEnum, provider)) {
                                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 deinitialize");
                            }
                            else if (flags.silent) {
                                const subx = (_c = clusterDefs.find(c => c.name == flags.name && c.provider == provider)) === null || _c === void 0 ? void 0 : _c.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.getAllClusterProviders(this.ioc);
                                        const csp = yield this.cspContextualizer.promptForCloudProvider(allPvds, undefined);
                                        const name = (yield this._ui.prompt("clusterName", "Name of the cluster to deinitialize:", true));
                                        const subx = (yield this._ui.prompt("clusterSubx", (csp == contracts_1.CloudProviderEnum.aws ? "AccountId" : "SubscriptionId").concat(" of the cluster to deinitialize:"), true));
                                        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 deinitialize:", choices));
                                            let def = clusterDefs.find(c => c.name === name);
                                            cluster = { name: name, provider: def.provider, providerSubscription: def.providerSubscription };
                                        }
                                    }
                                    confirm = yield this._ui.promptConfirm("confirmDeinit", `Deinitialize the cluster: ${this._styler.hilite(this.describe(cluster))} ? `, 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(`Deinitializing cluster: ${this._styler.hilite(cluster.name)}`);
                                    let resultIngress = yield this.genRelayClient.Call.clusterDeinit({ clusterName: cluster.name });
                                    this._ui.stopSpinner(resultIngress.success ? "SUCCESS" : "FAILED");
                                    let msg = `Cluster Deinitialize ${resultIngress.success ? "SUCCESS" : "FAILED"}: ${resultIngress.message || ""}`;
                                    this.logger.debug(msg, resultIngress);
                                    this._ui.userMessage(msg);
                                }
                                else {
                                    this._ui.userMessage("Operation cancelled.  No work was done.");
                                }
                            }
                        }
                        catch (err) {
                            this.handleError(err);
                        }
                        finally {
                            yield this.closeConnections();
                            resolve();
                        }
                    }));
                }
                catch (err) {
                    this.handleError(err);
                }
                finally {
                    yield this.closeConnections();
                    resolve();
                }
            }));
        });
    }
    /** Renders a user-friendly cluster description. */
    describe(cluster) {
        return `${cluster.name} ${this._styler.dim("(" + cluster.provider + (cluster.locationName ? ", " + cluster.locationName : "") + ")")}`;
    }
}
exports.default = NocClusterDeinit;
NocClusterDeinit.description = 'Deinitialization of the cluster (uninstalls the ingress controller and tls cert manager services)';
NocClusterDeinit.aliases = ["cluster:deinit"];
NocClusterDeinit.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    name: core_1.Flags.string({ char: 'n', required: false, description: 'Name of the cluster.' }),
    provider: core_1.Flags.string({ char: 'p', options: Object.keys(contracts_1.CloudProviderEnum), required: false, description: 'Code for the cloud service provider.' }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: ["name"], required: false, description: `(Optional: defaults to false) Prevents interactive user-interface and throws if interaction is needed. Requires arguments: [--name -n]` })
};
NocClusterDeinit.args = {
// name: Args.string({ description: 'Name of existing cluster.' })
};
//# sourceMappingURL=deinit.js.map