"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const YAML = require("yaml");
const jmespath = require("jmespath");
const command_base_exec_tenant_1 = require("../../command-base-exec-tenant");
const _ = require("lodash");
const render = require("../../uilogic/render-methods");
const render_methods_1 = require("../../uilogic/render-methods");
class EnterpriseList extends command_base_exec_tenant_1.CommandBaseExecTenant {
    constructor() {
        super(...arguments);
        this._outputFormat = render_methods_1.OutputFormatsEnum.tree;
    }
    captureArgs() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(EnterpriseList);
            if (flags.output) {
                this._outputFormat = (_a = flags.output) !== null && _a !== void 0 ? _a : render_methods_1.OutputFormatsEnum.tree;
            }
            else if (!_.isEmpty(flags.query)) {
                this._outputFormat = render_methods_1.OutputFormatsEnum.json;
            }
            else {
                this._outputFormat = render_methods_1.OutputFormatsEnum.tree;
            }
            if (!_.isEmpty(flags.query) && [render_methods_1.OutputFormatsEnum.text, render_methods_1.OutputFormatsEnum.tree].includes(this._outputFormat)) {
                throw new Error("Cannot use text or tree output format with the --query parameter.");
            }
            this._query = flags.query;
            return [{}, false];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return {};
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return {};
        });
    }
    buildCommandString(candidate, cmd) {
        if (this._outputFormat !== render_methods_1.OutputFormatsEnum.tree)
            cmd.push("-o", this._outputFormat);
        if (this._query)
            cmd.push("-q", this._query);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const isStructured = [render_methods_1.OutputFormatsEnum.json, render_methods_1.OutputFormatsEnum.yaml].includes(this._outputFormat);
            if (!isStructured)
                this._ui.startSpinner("Retrieving");
            let enterprises = yield this._codiacApi.Enterprise.readMany({ all: true });
            if (!isStructured)
                this._ui.stopSpinner(`found ${enterprises.length}`);
            let list = _.sortBy(enterprises.map(ent => ({ name: ent.code })), e => e.name);
            if (this._query && !_.isEmpty(this._query.trim())) {
                list = jmespath.search(list, this._query);
            }
            let output = "";
            switch (this._outputFormat) {
                case render_methods_1.OutputFormatsEnum.json:
                    output = JSON.stringify(list, undefined, 2);
                    this._ui.userMessage(output);
                    break;
                case render_methods_1.OutputFormatsEnum.yaml:
                    output = YAML.stringify(list, { indent: 2 });
                    this._ui.userMessage(output);
                    break;
                case render_methods_1.OutputFormatsEnum.text:
                    output = render.renderStringList(list.map(e => e.name));
                    this._ui.userMessage(output);
                    break;
                case render_methods_1.OutputFormatsEnum.tree:
                default:
                    output = render.renderStringTree(list.map(e => ({ text: e.name })));
                    this._ui.userMessage(output);
                    break;
            }
        });
    }
}
exports.default = EnterpriseList;
EnterpriseList.description = 'Shows the list of enterprises.';
EnterpriseList.aliases = ["ent:list"];
EnterpriseList.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    output: core_1.Flags.string({
        char: 'o',
        description: "Format in which to render the results.",
        options: ["text", "tree", "json", "yaml"],
    }),
    query: core_1.Flags.string({
        char: 'q',
        description: "JMESPath expression to filter or reshape the results (see jmespath.org).",
    }),
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Executes without any user interaction; fails on missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Renders the equivalent non-interactive command for future use before executing.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Renders the equivalent non-interactive command without executing it.' }),
};
EnterpriseList.args = {};
EnterpriseList.examples = [
    { description: "Simple listing.", command: "<%= config.bin %> <%= command.id %>" },
    { description: "List of enterprise names only.", command: "<%= config.bin %> <%= command.id %> -q '[].name'" },
    { description: "Multi-property projection.", command: "<%= config.bin %> <%= command.id %> -q '[].{ name: name }'" },
    { description: "Filter by name.", command: "<%= config.bin %> <%= command.id %> -q \"[?name == 'myEnterprise']\"" },
    { description: "Export as YAML.", command: "<%= config.bin %> <%= command.id %> -o yaml" },
    { description: "Non-interactive invocation.", command: "<%= config.bin %> <%= command.id %> --silent" },
    { description: "Renders the equivalent silent command without executing.", command: "<%= config.bin %> <%= command.id %> --to-script" },
];
//# sourceMappingURL=list.js.map