"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecretStoreUiLogic = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const YAML = require("yaml");
const command_base_exec_1 = require("../../command-base-exec");
const config_ui_utils_1 = require("../../uilogic/config-ui-utils");
const prettify_1 = require("../../prettify");
const _ = require("lodash");
const output_format_enum_1 = require("../../cli-entities/output-format-enum");
const contracts_1 = require("../../apis/codiac-relay/contracts");
const contracts_2 = require("../../relay/contracts");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
class SecretStoreUiLogic {
    /** COnverts to the name of the kvp store technology WITHOUT the cloud provider prefix.
     * eg: `azKeyVault` converts to `"Key Vault"`
     */
    static friendlyNameFor(type) {
        switch (type) {
            case contracts_2.KvpStoreTypesEnum.awsKeyVault: return "SecretStore";
            case contracts_2.KvpStoreTypesEnum.azKeyVault: return "KeyVault";
            case contracts_2.KvpStoreTypesEnum.azBlob: return "BlobStorage";
            default: return type.toString();
        }
    }
    static locationNameFor(entity) {
        var _b, _c, _d, _e, _f;
        return (_f = (_e = (_c = (_b = entity.instance) === null || _b === void 0 ? void 0 : _b.location) !== null && _c !== void 0 ? _c : (_d = entity.instance) === null || _d === void 0 ? void 0 : _d.region) !== null && _e !== void 0 ? _e : entity.location) !== null && _f !== void 0 ? _f : entity.region;
    }
    static displayNameFor(entity, styler) {
        var _b, _c, _d, _e;
        let display = styler.hilite(entity.name).concat(" ", styler.dim(this.friendlyNameFor(entity.type)), styler.dim(" on "), (_b = entity.provider) !== null && _b !== void 0 ? _b : (_c = entity.instance) === null || _c === void 0 ? void 0 : _c.provider, this.locationNameFor(entity) ? styler.dim(" (" + this.locationNameFor(entity) + ")") : "");
        if (((_d = entity.instance) === null || _d === void 0 ? void 0 : _d.name) != entity.name)
            display = display.concat(styler.dim(" (as " + ((_e = entity.instance) === null || _e === void 0 ? void 0 : _e.name) + ")"));
        return display;
    }
}
exports.SecretStoreUiLogic = SecretStoreUiLogic;
class SecretStoreList extends command_base_exec_1.CommandBaseExec {
    toStoreType(typeFlag) {
        switch (typeFlag) {
            case "aws-secrets": return contracts_2.KvpStoreTypesEnum.awsKeyVault;
            case "az-key-vault": return contracts_2.KvpStoreTypesEnum.azKeyVault;
            default: return type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_2.KvpStoreTypesEnum, typeFlag);
        }
    }
    toTypeFlag(type) {
        var _b;
        switch (type) {
            case contracts_2.KvpStoreTypesEnum.awsKeyVault: return "aws-secrets";
            case contracts_2.KvpStoreTypesEnum.azKeyVault: return "az-key-vault";
            default: return (_b = type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_2.KvpStoreTypesEnum, type)) !== null && _b !== void 0 ? _b : "";
        }
    }
    captureArgs() {
        var _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(SecretStoreList);
            let partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.provider)
                partial.provider = type_safety_utils_1.TypeSafetyUtils.toEnum(contracts_1.CloudProviderEnum, flags.provider);
            if (flags.type)
                partial.type = this.toStoreType(flags.type);
            if (flags.output)
                partial.outputFormat = type_safety_utils_1.TypeSafetyUtils.toEnum(output_format_enum_1.OutputFormatEnum, flags.output);
            // ---------------------------------------------------------------
            // TODO: move everything from here down into the base class
            // ---------------------------------------------------------------
            const interactionMode = (this.pipedInput) ? config_ui_utils_1.InteractionModes.silent : (_c = (_b = undefined !== null && undefined !== void 0 ? undefined : (flags.echo ? config_ui_utils_1.InteractionModes.echo : undefined)) !== null && _b !== void 0 ? _b : (flags["to-script"] ? config_ui_utils_1.InteractionModes.toscript : undefined)) !== null && _c !== void 0 ? _c : (flags.silent ? config_ui_utils_1.InteractionModes.silent : undefined);
            const takeDefaults = flags['take-defaults'];
            return [partial, interactionMode, takeDefaults];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        var _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let candidate = {
                enterprise: partial.enterprise,
                outputFormat: (_b = partial.outputFormat) !== null && _b !== void 0 ? _b : output_format_enum_1.OutputFormatEnum.auto
            };
            if (partial.type)
                candidate.type = partial.type;
            if (partial.provider)
                candidate.provider = partial.provider;
            if (!partial.type && !partial.provider)
                candidate.all = true;
            return candidate;
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // TODO: Add interactive prompts for provider and type 
            return this.buildCandidate_silently(partial, rootMap);
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.provider)
            cmd.push("--provider", candidate.provider);
        if (candidate.type)
            cmd.push("--type", this.toTypeFlag(candidate.type));
        if (candidate.enterprise)
            cmd.push("--enterprise", candidate.enterprise);
        if (candidate.outputFormat)
            cmd.push("-o", candidate.outputFormat);
        // TODO: Capture takeDefaults
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // Commented out bc the relay endpoint requires provider, and we want it as an optional filter
            // --------------------------------------------------------------------------------------------------------------------------------
            // let req: GetSecretStoresRequest = {
            //   provider: candidate.provider,
            //   spec: candidate
            // };
            // 
            // let output: string;
            // let listRes = await this.genRelayClient.Call.GetSecretStores({ provider: candidate.provider, spec: req })
            // if (listRes.error) throw listRes.error;
            // 
            // output = this.renderAs(listRes.output ?? [], candidate.outputFormat, x => SecretStoreUiLogic.displayNameFor(x, this._styler));
            // --------------------------------------------------------------------------------------------------------------------------------
            let req = Object.assign({}, _.omit(candidate, "enterprise", "outputFormat"));
            let list = yield this._codiacApi.KvpStoreDef.readMany(req);
            let output = this.renderAs(list, candidate.outputFormat, entity => SecretStoreUiLogic.displayNameFor(entity, this._styler));
            console.log(output);
        });
    }
    /** TODO: This method is generic.  Promote it to a shared utility lib. */
    renderAs(list, format, textFormatter) {
        let output = "";
        switch (format) {
            case output_format_enum_1.OutputFormatEnum.json:
                output = JSON.stringify(list, undefined, 2);
                break;
            case output_format_enum_1.OutputFormatEnum.yaml:
                output = YAML.stringify(list, { indent: 2 });
                break;
            case output_format_enum_1.OutputFormatEnum.pretty:
            case output_format_enum_1.OutputFormatEnum.auto:
            default:
                if (list.length > 0) {
                    if (textFormatter) {
                        output = list.map(x => textFormatter(x)).join("\n");
                    }
                    else {
                        output = (0, prettify_1.prettify)(list);
                    }
                }
                else {
                    output = "None found.";
                }
                break;
        }
        return output;
    }
}
exports.default = SecretStoreList;
_a = SecretStoreList;
SecretStoreList.description = 'Retrieves the list of existing secret stores captured for a given enterprise.';
SecretStoreList.examples = [
    '<%= config.bin %> <%= command.id %>',
];
/** The values that this command supports for the "type" flag.  */
SecretStoreList.STORE_TYPE_OPTIONS = ["aws-secrets", "az-key-vault"];
SecretStoreList.flags = {
    enterprise: core_1.Flags.string({ char: 'e', description: '(optional if there is only one) The enterprise for which the secret stores have been captured.' }),
    // COMMENTED OUT BC: kvp stores arent getting their provider property hydrated (TODO: Determine if its obsolete or not), so this always returns empty results.
    // provider: Flags.string({ char: 'p', options: [CloudProviderEnum.aws, CloudProviderEnum.azure], required: false, description: "The cloud provider hosting the secret store." }),
    type: core_1.Flags.string({ char: 't', options: _a.STORE_TYPE_OPTIONS, required: false, description: "The cloud provider hosting the secret store." }),
    // output list, table, json, yaml (wd love to have jmespath and/or a template and/or a projection)
    output: core_1.Flags.string({ char: 'o', default: output_format_enum_1.OutputFormatEnum.auto, description: "format in which to render the data.", options: [output_format_enum_1.OutputFormatEnum.json, output_format_enum_1.OutputFormatEnum.yaml, output_format_enum_1.OutputFormatEnum.auto] }),
    // TODO: Move these into the base class
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], 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": core_1.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." })
};
SecretStoreList.args = {};
//# sourceMappingURL=list.js.map