"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const command_base_enterprise_1 = require("../command-base-enterprise");
const codiac_constants_1 = require("../codiac-constants");
const prettify_1 = require("../prettify");
class Whereami extends command_base_enterprise_1.CommandBaseEnterprise {
    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 _a, _b, _c;
                try {
                    this.bootstrap();
                    const { args, flags } = yield this.parse(Whereami);
                    let bindings = {
                        tenant: (_b = (_a = this._projCfg) === null || _a === void 0 ? void 0 : _a.tenantCode) !== null && _b !== void 0 ? _b : this._userCntx.currentTenantCode
                        // , currentBranch: await this._ops.gitCurrentBranchNameFor(this._projectRoot)
                    };
                    if ((_c = this._projUserCfg) === null || _c === void 0 ? void 0 : _c.enterprise) {
                        bindings.enterprise = this._projUserCfg.enterprise.enterpriseCode;
                        if (this._projUserCfg.enterprise.cabinet) {
                            let environment = yield this.getEnvironmentFor(this._projUserCfg.enterprise.cabinet.cabinet);
                            bindings.environment = environment || "[unassigned]";
                            bindings.cabinet = this._projUserCfg.enterprise.cabinet.cabinet;
                            // bindings.cabinetBranch = this._projUserCfg.enterprise.cabinet.branch;  // Support was never built for cabinet branch bindings, and now it's in the way (#wannabeagile).
                        }
                        if (this._projUserCfg.enterprise.assetBindings && this._projUserCfg.enterprise.assetBindings.length > 0) {
                            bindings.assets = [];
                            for (let assetBinding of this._projUserCfg.enterprise.assetBindings) {
                                bindings.assets.push({
                                    asset: assetBinding.incarnation.assetName,
                                    image: assetBinding.image.name
                                });
                            }
                        }
                    }
                    this._ui.userMessage((0, prettify_1.prettify)(bindings));
                    /* Cheap-ass requirement doc below:
                    
                    Jun 4, 2020
                    Ben  11:17 AM
                    i need to know which enviroment im in
                    or at least, which environment you built against
                
                    Mark Freydl  11:18 AM
                    there’s an enterprise context that gets stored in the project-user config file (edited)
                    that states the current enterprise, cabinet and asset bindings that the user is pointing the project to (all that is based on gthe branch and cabinet-to-bramch binding, so it’s not source code 0- it’s local state)
                
                    Ben  11:20 AM
                    yeah, that works
                    forgot we have in the domain
                    that'd be a fun whoami
                
                    Mark Freydl  11:21 AM
                    Every time I work with Environment, I keep thinking that it doesnt have any real purpose other than being a tag
                    good idea
                    maybe a “whereami”
                
                    Ben  11:21 AM
                    fuck yes dude
                
                    Mark Freydl  11:21 AM
                    returns your enteprise context
                    and branch maybe
                
                    Ben  11:22 AM
                    always right, easy to access, i like it
                
                    Mark Freydl  11:27 AM
                    You should write that one.
                    it shd be easy - just need to use the cfgRepo to load the projectUser config and prob localOps to get the current branch info
                
                    Ben  11:30 AM
                    i'd be happy to.
                    
                    */
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
                finally {
                    yield this.closeConnections();
                }
            }));
        });
    }
    /** Returns undefined if the cabinet has no environment
     * (undefined should never happen but if such a data issue existed, it would be VERY helpful to know about it here).
     * On error, this method logs the error and returns ERROR_INDICATOR as output.    */
    getEnvironmentFor(cabinet) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                let environment;
                try {
                    let result = yield this._codiacApi.Cabinet.tryReadMany({ name: { $eq: cabinet } });
                    if (result.error)
                        throw result.error;
                    else if (result.output && result.output.length > 0) {
                        environment = result.output[0].environment;
                    }
                }
                catch (err) {
                    this.logger.debug(`Error retrieving environment for cabinet [${cabinet}, tenant: ${this._userCntx.currentTenantCode}]: ${err.name || ""} ${err.message || ""}`, err);
                    environment = codiac_constants_1.ERROR_INDICATOR;
                }
                finally {
                    // HACK: idkwtf we have to bam this from one TS version to another
                    resolve(environment);
                }
            }));
        });
    }
}
exports.default = Whereami;
Whereami.description = 'Renders the current cabinet context the image project is pointed to.  ie:  Tenant, Enterprise, Environment, Cabinet.';
Whereami.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    // flag with a value (-n, --name=VALUE)
    name: core_1.Flags.string({ char: 'n', description: 'name to print' }),
    // flag with no value (-f, --force)
    force: core_1.Flags.boolean({ char: 'f' }),
};
Whereami.args = {};
//# sourceMappingURL=whereami.js.map