"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const contracts_1 = require("../../../apis/codiac-api/contracts");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
const type_safety_utils_1 = require("../../../uilogic/type-safety-utils");
class NocClusterDeinit extends command_base_exec_tenant_1.CommandBaseExecTenant {
    captureArgs() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(NocClusterDeinit);
            return [{}, false];
        });
    }
    buildCandidate_silently(_partial, _rootMap) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(NocClusterDeinit);
            if (!flags.name)
                throw new Error(`Cluster name (--name / -n) is required in silent mode.`);
            const provider = (flags.provider) ? type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, flags.provider) : undefined;
            if (!provider)
                throw new Error(`Cloud provider (--provider / -p) is required in silent mode.`);
            const crit = { privateOwner: (_a = this._userCntx) === null || _a === void 0 ? void 0 : _a.currentTenantCode };
            const projection = { pathsIncluded: ["id", "name", "provider", "providerSubscription", "locationName", "privateOwner", "instance"], pathsExcluded: [] };
            const readResult = yield this._codiacApi.ClusterDef.tryReadMany(crit, { projection: projection });
            const clusterDefs = ((_b = readResult.output) !== null && _b !== void 0 ? _b : []).map(c => c).filter(c => c.instance != undefined);
            const found = clusterDefs.find(c => c.name === flags.name && c.provider === provider);
            if (!found)
                throw new Error(`Cluster [${flags.name}] not found for provider [${provider}].`);
            return { cluster: { name: found.name, provider: found.provider, providerSubscription: found.providerSubscription } };
        });
    }
    buildCandidate_interactively(_partial, _takeDefaults, _rootMap) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(NocClusterDeinit);
            const provider = (flags.provider) ? type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, flags.provider) : undefined;
            const crit = { privateOwner: (_a = this._userCntx) === null || _a === void 0 ? void 0 : _a.currentTenantCode };
            const projection = { pathsIncluded: ["id", "name", "provider", "providerSubscription", "locationName", "privateOwner", "instance"], pathsExcluded: [] };
            const readResult = yield this._codiacApi.ClusterDef.tryReadMany(crit, { projection: projection });
            let clusterDefs = ((_b = readResult.output) !== null && _b !== void 0 ? _b : []).map(c => c).filter(c => c.instance != undefined);
            if (type_safety_utils_1.TypeSafetyUtils.isEnum(contracts_1.CloudProviderEnum, provider)) {
                clusterDefs = clusterDefs.filter(c => c.provider === provider);
            }
            if (readResult.error === undefined && clusterDefs.length === 0) {
                this._ui.userMessage("No clusters exist with instances to deinitialize.");
                return undefined;
            }
            let cluster;
            let confirmed = false;
            const candidate = {};
            if (flags.name)
                candidate.name = flags.name;
            do {
                if (readResult.error) {
                    const 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, provider: csp, providerSubscription: subx };
                }
                else {
                    const found = candidate.name ? clusterDefs.find(c => c.name === candidate.name) : undefined;
                    if (found) {
                        cluster = found;
                    }
                    else {
                        const choices = clusterDefs.map(c => ({ name: this.describe(c), value: c.name }));
                        const name = (yield this._ui.promptSelect("clusterName", "Select the cluster to deinitialize:", choices));
                        const def = clusterDefs.find(c => c.name === name);
                        cluster = { name, provider: def.provider, providerSubscription: def.providerSubscription };
                    }
                }
                confirmed = yield this._ui.promptConfirm("confirmDeinit", `Deinitialize the cluster: ${this._styler.hilite(this.describe(cluster))} ?`, false);
                if (!confirmed)
                    candidate.name = undefined;
            } while (!confirmed);
            yield this.cspContextualizer.promptForCloudProviderCreds(this.ioc, cluster.provider, undefined, undefined, undefined, cluster.providerSubscription);
            return { cluster: cluster };
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("-n", candidate.cluster.name);
        cmd.push("-p", candidate.cluster.provider);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { cluster } = candidate;
            const result = yield this.watcher.triggerAndWatch((correlationId, socketId) => this.genRelayClient.Call.clusterDeinit({ spec: { clusterName: cluster.name }, socketId, correlationId }));
            const msg = `Cluster Deinitialize ${result.success ? "SUCCESS" : "FAILED"}: ${result.message || ""}`;
            this.logger.debug(msg, result);
            this._ui.userMessage(msg);
        });
    }
    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 to deinitialize.' }),
    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({ exclusive: ["echo", "to-script"], description: 'Executes without any user interaction; fails on missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Renders the equivalent non-interactive command for future use before executing.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Renders the equivalent non-interactive command without executing it.' }),
};
NocClusterDeinit.args = {};
NocClusterDeinit.examples = [
    { description: "Deinitialize a cluster interactively.", command: "<%= config.bin %> <%= command.id %>" },
    { description: "Non-interactive invocation.", command: "<%= config.bin %> <%= command.id %> -n my-cluster --silent" },
    { description: "Renders the equivalent silent command without executing.", command: "<%= config.bin %> <%= command.id %> -n my-cluster --to-script" },
];
//# sourceMappingURL=deinit.js.map