"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const cli_common_1 = require("../../cli-common");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const uilogic_1 = require("../../uilogic");
const ops_1 = require("../../ops");
class TenantCreate extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                const { args, flags } = yield this.parse(TenantCreate);
                if (this._projCfg && this._projCfg.tenantCode !== undefined && this._projCfg.tenantCode !== ops_1.DxConstants.UNREGISTERED_TENANT_CODE) {
                    // this._ui.userMessage(`Cannot switch tenant from within a project folder.`)
                    throw new Error(`Current tenant [${this._styler.hilite(this._projCfg.tenantCode)}]; cannot switch tenant from this folder; it exists within a workspace declared for that tenant (see the nearest codiac.json file).`);
                }
                // this._userCntx = await this.promptForNewTenant(this._userCntx, contextor);
                let contextor = new uilogic_1.TenantContextualizer(this.cliEnviro, this._projCfg, this.authClient, this.projCfgRepo, this._ui, this._styler, this.logger);
                this._userCntx = yield this.establishTenantContext(this._userCntx, contextor);
                let newCntx;
                if (args.code) {
                    newCntx = yield contextor.trySwitchTenant(this._userCntx, args.code);
                }
                newCntx = newCntx !== null && newCntx !== void 0 ? newCntx : yield contextor.trySelectFromMyTenants(this._userCntx, false);
                if (newCntx !== undefined) {
                    this._userCntx = newCntx;
                    this.bindUserInIoc(this._userCntx);
                    if (this._userCntx.currentTenantCode) {
                        this._ui.userMessage(`Switched to tenant [${this._styler.hilite(this._userCntx.currentTenantCode)}]`);
                    }
                    else {
                        this._ui.userMessage(`Current user context is tenant-less.`);
                    }
                }
            }
            catch (err) {
                this.handleError(err);
            }
            finally {
                yield this.closeConnections();
                return;
            }
        });
    }
    /** Logs the user in as needed, and persists the new context object to the local machine. */
    promptForNewTenant(currentContext, contextor) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let cntx = yield contextor.tryRegisterNewTenant(currentContext);
                    if (cntx == undefined) {
                        // this._ui.userMessage(`${this._styler.colorCritical("ERROR")} Unable to create a new Tenant`);
                        throw new Error(`${this._styler.colorCritical("ERROR")} Unable to create a new Tenant`);
                    }
                    else {
                        if (cntx.currentToken)
                            this._codiacApi.setUserToken(cntx.currentToken); // why isnt this being done by the contextualizer?
                        this.bindUserInIoc(cntx);
                    }
                    resolve(cntx);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
}
exports.default = TenantCreate;
TenantCreate.description = "Sets a different tenant context from the current user's list of tenants.";
TenantCreate.args = {
    code: core_1.Args.string({ required: false, description: 'The unique string identifying the tenant to switch to.' })
};
TenantCreate.flags = Object.assign(Object.assign({}, cli_common_1.commandBase.globalFlags), { help: core_1.Flags.help({ char: 'h' }) });
//# sourceMappingURL=switch.js.map