"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 ops_1 = require("../../ops");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const uilogic_1 = require("../../uilogic");
class TenantCreate extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                this.bootstrap();
                let params = yield this.parse(TenantCreate);
                return this.exec.runWithDefaults(params, (args, flags) => 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* () {
                            // this._ui.userMessage(`This command is not yet supported.`);
                            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(`Cannot switch tenant from within a project folder with a tenant declared.`);
                            }
                            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 newCtnx = yield contextor.establishPrincipalContext(this._userCntx);
                            newCtnx = yield this.promptForNewTenant(this._userCntx, contextor, flags.name, flags.code);
                            if (newCtnx !== undefined) {
                                this._userCntx = newCtnx;
                                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;
                    }
                }));
            }
            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, companyName, tenantCode) {
        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, companyName, tenantCode);
                    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 = 'Registers a new tenant with the current user as the administrator.';
TenantCreate.args = {
    name: core_1.Args.string({ required: false, description: 'The name of the tenant to create' })
};
TenantCreate.flags = Object.assign(Object.assign({}, cli_common_1.commandBase.globalFlags), { name: core_1.Flags.string({ char: 'n', description: "Full name of the tenant organization." }), code: core_1.Flags.string({ char: 'c', description: "(Optional, not recommended) Proposed human readable unique identifier code for the tenant origanization.  This command will fail if the given tenant code is already taken." }), silent: core_1.Flags.boolean({ char: 'y', dependsOn: ["name", "code"], description: "Suppresses user interaction." }), help: core_1.Flags.help({ char: 'h' }) });
//# sourceMappingURL=create.js.map