"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CspCredsList = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const YAML = require("yaml");
const contracts_1 = require("../../../apis/codiac-api/contracts");
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 type_safety_utils_1 = require("../../../uilogic/type-safety-utils");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
class CspCredsList extends command_base_exec_tenant_1.CommandBaseExecTenant {
    captureArgs() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(CspCredsList);
            let partial = {};
            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 : (_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 = {
                outputFormat: (_a = partial.outputFormat) !== null && _a !== void 0 ? _a : output_format_enum_1.OutputFormatEnum.auto
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let candidate = {
                outputFormat: (_a = partial.outputFormat) !== null && _a !== void 0 ? _a : output_format_enum_1.OutputFormatEnum.auto
            };
            return candidate;
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.outputFormat)
            cmd.push("-o", candidate.outputFormat);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let req = Object.assign({}, _.omit(candidate, "outputFormat"));
            let result = yield this.genRelayClient.Call.get_csp_creds_list(req);
            if (result.error)
                throw result.error;
            if (result.output) {
                let output = this.renderAs(result.output, candidate.outputFormat, x => CspCredsList.renderCspCred(x, this._styler));
                this._ui.userMessage(output);
            }
            else if (result.success == false) {
                this._ui.userMessage(this._styler.colorCritical("Failed").concat(" retrieving credentials list: ", (_a = result.message) !== null && _a !== void 0 ? _a : "(no details available)"));
            }
            else {
                this._ui.userMessage("none found.");
            }
        });
    }
    static renderCspCred(cred, styler) {
        const output = [styler.hilite(cred.provider), cred.subscriptionId, cred.username, cred.expiration ? "Expires: ".concat(cred.expiration.toLocaleDateString()) : undefined].filter(x => x != undefined).join(" | ");
        return output;
    }
    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 (textFormatter) {
                    output = list.map(x => textFormatter(x)).join("\n");
                }
                else {
                    output = (0, prettify_1.prettify)(list);
                }
                break;
        }
        return output;
    }
}
exports.CspCredsList = CspCredsList;
CspCredsList.description = 'Retrieves the list of Cloud Service Provider credentials for the current user.';
CspCredsList.examples = [
    '<%= config.bin %> <%= command.id %>',
];
CspCredsList.flags = {
    provider: core_1.Flags.string({ char: 'p', options: Object.keys(contracts_1.CloudProviderEnum), description: 'Code indicating the Cloud Service Provider (CSP) to search on' }),
    subscriptionId: core_1.Flags.string({ char: 's', description: 'The Id of the cloud provider subscription to filter on.' }),
    cspTenantId: core_1.Flags.string({ char: 't', description: 'The Id of the cloud provider tenant to filter on.' }),
    // providerSubscriptionId
    // providerTenantId
    // 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." })
};
CspCredsList.args = {};
//# sourceMappingURL=list.js.map