"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileStoreUiLogic = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const YAML = require("yaml");
const _ = require("lodash");
const contracts_1 = require("../../apis/codiac-api/contracts");
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 output_format_enum_1 = require("../../cli-entities/output-format-enum");
class FileStoreUiLogic {
    /** 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_1.FileStoreTypeEnum.AzureBlobStorage: return "BlobStorage";
            case contracts_1.FileStoreTypeEnum.AzureDisk: return "Disk";
            case contracts_1.FileStoreTypeEnum.AzureFileStorage: return "FileStorage";
            default: return type.toString();
        }
    }
    /** Because the `provider` property is not yet part of FileStoreDef. */
    static deriveCspFor(entity) {
        switch (entity.type) {
            case contracts_1.FileStoreTypeEnum.AzureBlobStorage: return contracts_1.CloudProviderEnum.azure;
            case contracts_1.FileStoreTypeEnum.AzureDisk: return contracts_1.CloudProviderEnum.azure;
            case contracts_1.FileStoreTypeEnum.AzureFileStorage: return contracts_1.CloudProviderEnum.azure;
            default: return undefined;
        }
    }
    static displayNameFor(entity, styler, hilite = true) {
        var _a;
        let csp = (_a = this.deriveCspFor(entity)) !== null && _a !== void 0 ? _a : "";
        let display = (hilite ? styler.hilite(entity.name) : styler.bold(entity.name)).concat(styler.dim(" (" + this.friendlyNameFor(entity.type) + ")"), " ", csp);
        if (csp == contracts_1.CloudProviderEnum.azure) {
            // if ((<AzureFileStoreDef>entity).storageAccount) {
            if (entity.storageAccount && (entity.storageAccount != entity.name)) {
                display = display.concat(styler.dim(" stgAcct: " + entity.storageAccount));
            }
        }
        if (entity.shareName != entity.name) {
            display = display.concat(styler.dim(" shared as "), entity.shareName);
        }
        return display;
    }
}
exports.FileStoreUiLogic = FileStoreUiLogic;
// -------------------------------------------------------
// TODO: Add enteprise property to the FileStoreDef
// -------------------------------------------------------
class FileStoreList 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(FileStoreList);
            let partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.type)
                partial.type = contracts_1.FileStoreTypeEnum[flags.type]; // TODO: Add this to the criteria
            if (flags.output)
                partial.outputFormat = 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 : (_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, takeDefaults];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let candidate = {
                enterprise: partial.enterprise,
                outputFormat: (_a = partial.outputFormat) !== null && _a !== void 0 ? _a : output_format_enum_1.OutputFormatEnum.auto
            };
            if (partial.type)
                candidate.type = partial.type;
            if (!candidate.type)
                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.enterprise) cmd.push("--enterprise", candidate.enterprise);
        if (candidate.type)
            cmd.push("--type", candidate.type.toString());
        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.FileStoreDef.readMany(req);
            let output = this.renderAs(list, candidate.outputFormat, entity => FileStoreUiLogic.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 = FileStoreList;
FileStoreList.description = 'Retrieves the list of existing file stores captured for a given enterprise.';
FileStoreList.examples = [
    '<%= config.bin %> <%= command.id %>',
];
/** The values that this command supports for the "type" flag.  */
FileStoreList.STORE_TYPE_OPTIONS = ["aws-secrets", "az-key-vault"];
FileStoreList.flags = {
    enterprise: core_1.Flags.string({ char: 'e', description: '(optional if there is only one) The enterprise in which the filestores are defined.' }),
    type: core_1.Flags.string({ char: 't', options: Object.values(contracts_1.FileStoreTypeEnum), required: false, description: "Filter on the filestore technology." }),
    // 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." })
};
FileStoreList.args = {};
//# sourceMappingURL=list.js.map