"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const contracts_1 = require("../../apis/codiac-relay/contracts");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const _ = require("lodash");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
class CspLogout extends command_base_enterprise_1.CommandBaseEnterprise {
    static get allPvds() {
        if (this._allPvds == undefined) {
            this._allPvds = Object.values(contracts_1.CloudProviderEnum); //this.cspUiFactory.getAllClusterProviders(this.ioc);  // TODO: this call is currently limited to cluster providers - we need the comprehensive list of CSPs in use.
            _.remove(this._allPvds, x => x == contracts_1.CloudProviderEnum.other);
            _.remove(this._allPvds, x => x == contracts_1.CloudProviderEnum.localMachine);
        }
        return this._allPvds;
    }
    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 _b, _c, _d, _e, _f;
                try {
                    this.bootstrap();
                    const { args, flags } = yield this.parse(CspLogout);
                    this._userCntx = yield this.establishTenantContext(this._userCntx);
                    let suppressConfirmations = Boolean(flags.silent === true);
                    // Select the CSP
                    let provider;
                    if (args.provider) {
                        const pvdAsEnum = type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, args.provider);
                        if (pvdAsEnum == undefined)
                            throw new Error("Unrecognized cloud provider.");
                        provider = pvdAsEnum;
                    }
                    else if (suppressConfirmations) {
                        throw new Error(`You must specify a cloud provider.`);
                    }
                    else {
                        // Select interactively
                        // let allPvds = this.cspUiFactory.getAllClusterProviders(this.ioc);  // we dont want just cluster providers here
                        provider = yield this.cspContextualizer.promptForCloudProvider(CspLogout.allPvds, undefined);
                    }
                    let cspAcct = { subscriptionId: flags.subscriptionId, tenantId: flags.tenantId };
                    const cspTenant = yield this.cspContextualizer.ensureCspTenant(provider, this._codiacApi, cspAcct, false);
                    if (cspTenant) {
                        cspAcct.tenantId = cspTenant.cspTenantId;
                        // remove an invalid user-provided subscriptionId
                        if (cspAcct.subscriptionId && !((_b = cspTenant.subscriptionIds) === null || _b === void 0 ? void 0 : _b.includes(cspAcct.subscriptionId))) {
                            delete cspAcct.subscriptionId;
                        }
                    }
                    // interactive sign-out flow
                    try {
                        let username = yield this.cspContextualizer.promptToLogout(this.ioc, provider, cspAcct, suppressConfirmations);
                        this._ui.userMessage(`${this._styler.colorGood("Success!")} Signed out from ${this._styler.hilite(provider)}.`);
                    }
                    catch (err) {
                        this._ui.userMessage(`${this._styler.colorCritical("FAILED")} ${(_c = err.name) !== null && _c !== void 0 ? _c : ""} ${(_d = err.message) !== null && _d !== void 0 ? _d : ""}`);
                    }
                    resolve();
                }
                catch (err) {
                    this.logger.error(err);
                    this._ui.userMessage(`${this._styler.colorCritical("ERROR")} ${(_e = err.name) !== null && _e !== void 0 ? _e : ""} ${(_f = err.message) !== null && _f !== void 0 ? _f : ""}`);
                    resolve();
                }
                finally {
                    yield this.closeConnections();
                }
            }));
        });
    }
}
exports.default = CspLogout;
_a = CspLogout;
CspLogout.description = 'Closes session with the given Cloud Service Provider (CSP), eg: aws, azure, docker.  Use this command to clear the local cache for your security account at that provider.';
CspLogout.examples = [
    'cod csp logout',
    'cod csp logout docker',
    'cod csp logout --silent azure',
];
// static dependsOn = ["provider"];  // this isnt the whole of the requirements
CspLogout.flags = {
    subscriptionId: core_1.Flags.string({ char: 's', description: '(in silent mode, either this or tenantId is required if you have more than one tenant profile on a given cloud provider) The Id of the cloud provider subscription under which to logout.' }),
    tenantId: core_1.Flags.string({ char: 't', description: '(in silent mode, either this or subscriptionId is required if you have more than one tenant profile on a given cloud provider) The Id of the cloud provider tenant under which to logout.' }),
    silent: core_1.Flags.boolean({ char: 'y', required: false, description: `(Optional: defaults to false) Suppresses any user-interaction.` })
};
CspLogout.args = {
    provider: core_1.Args.string({ required: false, options: _a.allPvds, char: 'p', description: 'Code indicating the Cloud Service Provider (CSP) being authenticated with.' })
};
//# sourceMappingURL=logout.js.map