"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const command_base_1 = require("../../cli-common/command-base");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const _ = require("lodash");
class CabinetObliterate extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                let cmdParams = yield this.parse(CabinetObliterate);
                return this.exec.runWithDefaults(cmdParams, (args, flags) => 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 {
                            (_a = this._relayContainer) === null || _a === void 0 ? void 0 : _a.ready$.subscribe(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
                                var _b;
                                try {
                                    let cabinetName = args.cabinet;
                                    // TODO:  Allow user to select from existing cabs
                                    // TODO:  Ensure that if the projCfg has a tenantCode, that establishTenantContext enforced it with the user authentication.
                                    // THAT IS:  Boot 'em if they're not part of this project's tenant.
                                    this._userCntx = yield this.establishTenantContext(this._userCntx);
                                    let rootMap = yield this.getRootMap();
                                    const interactionMode = this.getInteractionMode(flags.silent, flags.echo, flags['to-script']);
                                    let enterprise = (yield this.establishEnterpriseContext(rootMap, flags.enterprise, interactionMode)).enterprise;
                                    _.remove(rootMap.enterprises, e => e.name != enterprise.name); // trim down to match legacy conditions
                                    // TODO: pass the rootMap and the current enterprise into each of these to prevent unnecessary api calls.
                                    let environment = yield this.establishEnvironment(flags.environment);
                                    let cabinetScope = yield this.establishCabinetContext(cabinetName, environment.code);
                                    // Get the clusterdef so we can get cloud pvd creds
                                    let cab = environment.cabinets.find(c => c.name === cabinetScope.cabinet);
                                    let cluster = (_b = cab.cluster) !== null && _b !== void 0 ? _b : ((rootMap.clusters.length === 1) ? rootMap.clusters[0].name : undefined); // fall back to the one and only.
                                    if (cluster === undefined) {
                                        this.logger.warn(`Cannot confirm cloud provider credentials: cabinet has no cluster specified. Process will rely on cached credentials.`);
                                        // throw new Error(`Cannot determine cloud provider: cabinet has no cluster specified.`);
                                    }
                                    else {
                                        yield this.establishCloudProviderCreds(rootMap, cluster);
                                    }
                                    // let cabinetScope = new CabinetScope(this._projUserCfg.enterprise.enterpriseCode, environment, cabinetName);
                                    // this.logger.detail(`Attempting cabinet obliterate [${JSON.stringify(cabinetScope)}]...`);
                                    yield this._ui.startSpinner(`Obliterating cabinet [${cabinetScope.enterprise}/${cabinetScope.environment}/${this._styler.hilite(cabinetScope.cabinet)}]...`);
                                    let result = yield this.genRelayClient.Call.postExecuteCabinetKiller({ target: cabinetScope });
                                    yield this._ui.stopSpinner(result.success ? "SUCCESS" : (result.error ? "ERROR" : "FAILED"));
                                    if (result.error) {
                                        this.logger.error(`Error obliterating cabinet: ${result.message || ""}; ${result.error.message}`, result.error);
                                        this._ui.userMessage(`Error obliterating cabinet: ${result.message || ""}; ${result.error.message}`);
                                    }
                                    else if (!result.success) {
                                        this.logger.notice(`Cabinet obliterate failed without error.  ${result.message}`);
                                        this._ui.userMessage(`Cabinet obliterate failed without error.  ${result.message}`);
                                    }
                                    else {
                                        this.logger.notice(`${this._styler.colorGood("Success!")} Cabinet [${cabinetScope.cabinet}] obliterated from enterprise [${cabinetScope.enterprise}]`);
                                        this._ui.userMessage(`${this._styler.colorGood("Success!")} Cabinet [${cabinetScope.cabinet}] obliterated from enterprise [${cabinetScope.enterprise}]`);
                                    } // else { this._ui.userMessage("Supposedly succeeded, but we didnt get the response back that we expected.  You might want to verify the cabinet."); }
                                }
                                catch (err) {
                                    this.handleError(err);
                                }
                            }));
                        }
                        catch (err) {
                            this.handleError(err);
                            reject(err);
                        }
                    }));
                }));
            }
            catch (err) {
                this.logger.error(`Error parsing arguments: ${err}`);
                this.logger.debug(err.stack);
                return new Promise((res, rej) => tslib_1.__awaiter(this, void 0, void 0, function* () { return res(); }));
                // return new Promise<void>(async (res,rej) => rej(new Error(`Error parsing arguments: ${err}`)));
            }
        });
    }
}
exports.default = CabinetObliterate;
CabinetObliterate.description = 'Hard-deletes an entire cabinet and everything in it; makes it as if the cabinet itself never existed.';
CabinetObliterate.aliases = ["cab:obliterate"];
CabinetObliterate.args = {
    cabinet: core_1.Args.string({ required: false, description: 'The name of the cabinet' })
};
CabinetObliterate.flags = Object.assign(Object.assign({}, command_base_1.commandBase.globalFlags), { help: core_1.Flags.help({ char: 'h' }), enterprise: core_1.Flags.string({ char: 'n', required: false, description: '(required only when more than one enterprise exists) The name of the enterprise containing the cabinet.' }), environment: core_1.Flags.string({ char: 'e', description: '(optional: defaults to that of the current project branch) The name of the environment this cabinet will be grouped under.' }) });
//# sourceMappingURL=obliterate.js.map