"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PROMPT_ME_DESIGNATOR = void 0;
const tslib_1 = require("tslib");
require("reflect-metadata");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const dom = require("@codiac.io/codiac-domain");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const output_format_enum_1 = require("../../cli-entities/output-format-enum");
const config_ui_utils_1 = require("../../uilogic/config-ui-utils");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
/** The value provided as input that indicates
 * a user's desire to be prompted with a list from which choose the value(s),
 * instead of entering them manually or taking a default. */
exports.PROMPT_ME_DESIGNATOR = "?";
class ConfigView extends command_base_enterprise_1.CommandBaseEnterprise {
    // --------------------------------------------------------------------
    // Lazy-loaded properties
    get configUtils() {
        if (this._configUtils_backer === undefined) {
            this._configUtils_backer = this.ioc.get(config_ui_utils_1.ConfigUiUtils);
        }
        return this._configUtils_backer;
    }
    // --------------------------------------------------------------------
    bootstrap() {
        super.bootstrap();
        this.ioc.bind(config_ui_utils_1.ConfigUiUtils).toSelf();
    }
    run() {
        var _a, _b, _c, _d;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.bootstrap();
            const { args, flags } = yield this.parse(ConfigView);
            try {
                this._userCntx = yield this.establishTenantContext(this._userCntx);
                let rootMap = yield this.getRootMap();
                const interactionMode = this.getInteractionMode(flags.silent, flags.echo, flags['to-script']);
                let enterprise = (yield this.establishEnterpriseContext(rootMap, flags.enterprise, interactionMode)).enterprise;
                _.remove(rootMap.enterprises, e => e.name != enterprise.name); // trim down to match legacy conditions
                // determine which asset
                let assetName;
                let assetType;
                let assetChanged;
                if (flags.asset == exports.PROMPT_ME_DESIGNATOR) {
                    [assetName, assetChanged, assetType] = yield this.configUtils.promptForAsset(enterprise.assets, flags.asset);
                    // let asset = await this.promptForAsset(enterprise.code);
                    // assetName = asset.name;
                }
                else if (flags.asset) {
                    [assetName, assetChanged, assetType] = yield this.configUtils.promptForAsset(enterprise.assets, flags.asset);
                    // let asset = await this.promptForAsset(enterprise.code, flags.asset);
                    // assetName = asset.name;
                }
                else {
                    // Update sync codiac with what we've got here in the project.
                    let requestedAssets = yield this.establishAssetContext(enterprise, flags.silent);
                    assetName = requestedAssets[0];
                    // let versions = await this.declareAssetVersions(requestedAssets, enterpriseCode);
                    // // We've updated Codiac.  Now trigger the deploy.
                    // assetVersions = requestedAssets.map(a => {
                    //   let version = versions.find(v => v.assetName == a);
                    //   return { a: a, v: version ? version.assetVersion : undefined };
                    // });
                }
                // let aCntx = await this.establishAssetContext(enterprise, true);
                // let selectedFile = (await this.enterpriseContextor.promptForTargetFile(enterprise.code, assetName, flags.file))!;
                let selectedFile = flags.file;
                let configType = flags.type ? type_safety_utils_1.TypeSafetyUtils.toEnum(dom.SpecialConfigTypesEnum, flags.type) : undefined;
                let settings;
                let typeFileChanged;
                // let existingSettings: ScopedSetting[] | undefined;
                [configType, selectedFile, settings, typeFileChanged] = yield this.configUtils.promptForTypeAndFile(enterprise.name, assetName, assetType, configType, selectedFile, undefined, false, false);
                /** The value of the targetFile property on the entity record.
                 *
                 * TODO: CHANGE this structure to treat file config types like any other config type.  (we're currently abusing this field bc of legacy design)
                 */
                let targetFileValue = selectedFile !== null && selectedFile !== void 0 ? selectedFile : `[${configType}]`;
                // let cab = await this.establishCabinet(flags.cabinet, flags.silent);
                let [cab, enviro] = yield this.configUtils.promptForCabinet(enterprise.name, rootMap, flags.cabinet, true);
                // if (flags.cabinet != undefined) {
                // await this.renderCabinetConfig(selectedFile, cab.enterpriseCode, cab.name, assetName, outputFormat);
                let outputFormat = (_a = type_safety_utils_1.TypeSafetyUtils.toEnum(output_format_enum_1.OutputFormatEnum, flags.output)) !== null && _a !== void 0 ? _a : output_format_enum_1.OutputFormatEnum.auto;
                let result = yield this.genRelayClient.Call.GetRenderedCabinetConfig({
                    configName: targetFileValue,
                    enterprise: enterprise.name,
                    cabinetName: cab.name,
                    assetName: assetName,
                    outputFormat: outputFormat
                }, { thisMachine: cab.thisMachine });
                if (result.success && result.output !== undefined) {
                    this._ui.userMessage(`${this._styler.hilite(targetFileValue)} for ${this._styler.hilite(enterprise.name)}/${this._styler.hilite(assetName)} in cabinet: [${this._styler.hilite(cab.name)}]`);
                    this._ui.userMessage(result.output);
                }
                else {
                    this._ui.userMessage((_d = (_b = result.message) !== null && _b !== void 0 ? _b : (_c = result.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : "Failed rendering");
                }
                // } else {
                //   await this.renderLocalConfig(selectedFile, args.setting, flags.prompt, outputFormat);
                // }
                return;
            }
            catch (err) {
                this.handleError(err);
                return;
            }
            finally {
                yield this.closeConnections();
            }
        });
    }
}
exports.default = ConfigView;
ConfigView.description = 'Retrieves a pre-deploy preview of the the ultimate configuration file contents for the given cabinet (with all inline variables and source references resolved).';
ConfigView.aliases = ['config:preview', 'cfg:preview'];
ConfigView.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    prompt: core_1.Flags.boolean({ char: 'p', default: false, description: 'Invokes a prompt to select from the existing settings.' }),
    enterprise: core_1.Flags.string({ char: 'e', required: false, description: 'The name of the enterprise that contains the asset. Required if there are more than one. (defaults to the current enterprise context)' }),
    asset: core_1.Flags.string({ char: 'a', required: false, description: `Search string for the name of the asset to deploy (use ${exports.PROMPT_ME_DESIGNATOR} to be prompted).` }),
    cabinet: core_1.Flags.string({ char: 'c', exclusive: ["enterprise", "environment"], description: 'The name of the cabinet to assemble the configuration for.' }),
    file: core_1.Flags.string({ char: 'f', required: false, default: 'app-config.json', description: 'The relative pathname of the config file to view (relative to the root of the codiac project).' }),
    type: core_1.Flags.string({ char: 't', exclusive: ["file"], options: Object.keys(dom.SpecialConfigTypesEnum), description: 'Filters for the settings types that do not land in a config file (such as... env: OS environment variables, footprint: container footprint specs, helm: helm chart settings, label: container meta labels, annotation: container platform key-value pairs).' }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: ["cabinet", "enterpriseCode"], required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values that are remembered from prior runs.` }),
    output: core_1.Flags.string({ char: 'o', required: false, default: output_format_enum_1.OutputFormatEnum.auto, options: [output_format_enum_1.OutputFormatEnum.pretty, output_format_enum_1.OutputFormatEnum.json, output_format_enum_1.OutputFormatEnum.yaml, output_format_enum_1.OutputFormatEnum.auto], description: "Output format of the actual settings data document." })
};
// enterpriseCode: flags.string({ char: 'e', required: false, description: `Code (name) of the enterprise of the owner asset` }),
ConfigView.args = {
    setting: core_1.Args.string({ description: '(optional) Name of specific setting value to view; omit to show all.', required: false })
};
ConfigView.examples = [
    '$ cod config:view',
    '$ cod config:view port',
    '$ cod config:view -p',
    '$ cod config:view -o pretty',
    '$ cod config:view -c dev2 -f settings.json -o pretty',
    '$ cod config:view -c dev2 -a myapi -t footprint'
];
//# sourceMappingURL=view.js.map