"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetWhere = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const command_base_exec_1 = require("../../command-base-exec");
const config_ui_utils_1 = require("../../uilogic/config-ui-utils");
const render = require("../../uilogic/render-methods");
class AssetWhere extends command_base_exec_1.CommandBaseExec {
    captureArgs() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(AssetWhere);
            let partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.asset)
                partial.asset = flags.asset;
            // ---------------------------------------------------------------
            // TODO: move everything from here down into the base class
            // ---------------------------------------------------------------
            const interactionMode = (this.pipedInput) ? config_ui_utils_1.InteractionModes.silent : (_b = (_a = undefined !== null && undefined !== void 0 ? undefined : (flags.echo ? config_ui_utils_1.InteractionModes.echo : undefined)) !== null && _a !== void 0 ? _a : (flags["to-script"] ? config_ui_utils_1.InteractionModes.toscript : undefined)) !== null && _b !== void 0 ? _b : (flags.silent ? config_ui_utils_1.InteractionModes.silent : undefined);
            // const takeDefaults = flags['take-defaults'];
            return [partial, interactionMode, false];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let ent = rootMap.enterprises.find(e => e.name == partial.enterprise);
            if (!ent)
                throw new Error("Enterprise not found."); // <-- todo: move this up to the base class and pass in the enterprise object.
            if (partial.asset == undefined)
                throw new Error("Missing asset name.");
            let asset = ent.assets.find(a => a.name == partial.asset);
            if (!asset)
                throw new Error("Asset not found");
            let candidate = {
                enterprise: partial.enterprise,
                asset: asset.name,
                rootMap: rootMap
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let ent = rootMap.enterprises.find(e => e.name == partial.enterprise);
            if (!ent) {
                ent = yield this.rootMapUtils.promptForEnterprise(partial, rootMap);
                partial.enterprise = ent.name;
            }
            let assetChanged;
            let assetType;
            [partial.asset, assetChanged, assetType] = yield this.rootMapUtils.promptForAsset(ent.assets, partial.asset);
            let candidate = {
                enterprise: partial.enterprise,
                asset: partial.asset,
                rootMap: rootMap
            };
            return candidate;
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--enterprise", candidate.enterprise);
        cmd.push("--asset", candidate.asset);
        // cmd.push("--id", candidate.id)
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let result = yield this._codiacApi.Call.assetWhere(candidate);
            if (result.error != undefined) {
                throw result.error;
            }
            else if ((result.success == true) && (result.output) && (result.output.length > 0)) {
                this._ui.userMessage(candidate.asset.concat(" is deployed to ", result.output.length.toString(), " cabinets:"));
                let embellisher = this.createAssetVersionEmbellisher(result.output);
                let cabTree = this.rootMapUtils.buildCabinetTree(candidate.rootMap, embellisher);
                let out = render.renderStringTree(cabTree);
                this._ui.userMessage(out);
            }
            else {
                this._ui.userMessage(candidate.asset.concat(" is not deployed anywhere."));
            }
        });
    }
    createAssetVersionEmbellisher(deployments) {
        let embellisher = {
            eachEnterprise: (entBranch, ent, rootMap) => {
                // entBranch.text = "(".concat(this._styler.hilite(rwd), ") ", entBranch.text);
            },
            eachEnviro: (envBranch, env, ent, rootMap) => {
                let dep = deployments.find(d => d.environment == env.name);
                if ((dep === null || dep === void 0 ? void 0 : dep.assetVersion) == undefined) {
                    envBranch.text = this._styler.dim(envBranch.text);
                }
            },
            eachCabinet: (cabBranch, cab, env, ent, rootMap) => {
                let dep = deployments.find(d => d.cabinet == cab.name);
                if (dep === null || dep === void 0 ? void 0 : dep.assetVersion) {
                    cabBranch.text = cabBranch.text.concat("  ", this._styler.hilite(dep.assetVersion));
                }
                else {
                    cabBranch.text = this._styler.dim(cabBranch.text);
                }
            },
        };
        return embellisher;
    }
}
exports.AssetWhere = AssetWhere;
AssetWhere.description = "Shows the cabinets to which the given asset is currently deployed and which version is where.";
AssetWhere.args = {};
AssetWhere.flags = {
    enterprise: core_1.Flags.string({ char: 'e', required: false, description: 'The name of the enterprise containing this asset. Required if there are more than one. (defaults to the current enterprise context)' }),
    asset: core_1.Flags.string({ char: 'a', required: false, description: "The name of the asset to show." }),
    // id: Flags.string({ required: false, description: "The system id of the enterprise asset to obliterate." }),
    // TODO: Move these into the base class
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], dependsOn: ["asset"], description: 'Non-Interactive mode; executes without any user interaction and fails on any missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Echo interaction mode; renders the equivalent non-interactive cli command for future use before final execution.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Toscript interaction mode; renders the equivalent non-interactive cli command WITHOUT any execution.' })
    // "take-defaults": Flags.boolean({ exclusive: ["silent"], description: "Setting this to true prevents prompting for confirmation on parameters that were passed in or were automatically set to default values (Irrelevant in --silent mode).  This behavior does NOT apply to scenarios that the command needs to override invalid user input; such cases will always prompt for confirmation.  eg: when no argument was provided for file or type, and only one exists, the system will render the autoselected file unless this flag is set." })
};
AssetWhere.examples = [
    '<%= config.bin %> <%= command.id %>',
    '<%= config.bin %> <%= command.id %> -a my-api',
    '<%= config.bin %> <%= command.id %> -e main -a my-api',
    '<%= config.bin %> <%= command.id %> -e main -a my-api --silent',
];
//# sourceMappingURL=where.js.map