"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const render = require("../../../uilogic/render-methods");
const command_base_exec_1 = require("../../../command-base-exec");
const config_ui_utils_1 = require("../../../uilogic/config-ui-utils");
class AuthRoleAllowed extends command_base_exec_1.CommandBaseExec {
    constructor() {
        super(...arguments);
        this.adminOnly = true;
    }
    captureArgs() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(AuthRoleAllowed);
            let partial = {};
            if (args.name && flags.id) {
                throw new Error("You must specify either the role name argument or the --id flag, not both.");
            }
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (args.name)
                partial.name = args.name;
            if (flags.id)
                partial.id = flags.id;
            // ---------------------------------------------------------------
            // 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];
        });
    }
    // /** Throws on invalid */
    // private validate(partial: Partial<IAuthRoleDef>): void {
    //   if (partial.name == undefined || _.isEmpty(partial.name)) throw new Error("Missing name");
    //   let rxName = /^[a-zA-Z][a-zA-Z0-9-]{2,50}$/;
    //   if (!rxName.test(partial.name)) throw new Error("Invalid name: must be 3- to 50-character string of alphanumerics and hyphens, starting with a letter.");
    // }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (partial.id == undefined && partial.name == undefined)
                throw new Error("Must specify either id or name.");
            let crit = {}; // <any>_.pick(partial, "id", "name")
            if (partial.name)
                crit.name = { $eq: partial.name };
            if (partial.id)
                crit.ids = [partial.id];
            let found = (yield this._codiacApi.AuthRole.readMany(crit, { throwNotFound: true }))[0]; // TODO: Get this from a cached secondary object
            let candidate = {
                enterprise: partial.enterprise,
                rootMap: rootMap,
                name: found.name
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return yield this.buildCandidate_silently(partial, rootMap);
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--enterprise", candidate.enterprise);
        if (candidate.id) {
            cmd.push("--id", candidate.id);
        }
        else if (candidate.name) {
            cmd.push("--name", candidate.name);
        }
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let embellisher = this.createRoleAccessEmbellisher(candidate.name);
            let cabTree = this.rootMapUtils.buildCabinetTree(candidate.rootMap, embellisher);
            let out = render.renderStringTree(cabTree); //, this._ui.userMessage);
            this._ui.userMessage("Privileges for role: ".concat(this._styler.hilite(candidate.name)));
            this._ui.userMessage(out);
            return;
        });
    }
    createRoleAccessEmbellisher(role) {
        let embellisher = {
            eachEnterprise: (entBranch, ent, rootMap) => {
                var _a;
                let rwd = this.dataAuthProvider.getRoleRwd(ent, role);
                entBranch.text = "(".concat(this._styler.hilite(rwd), ") ", entBranch.text);
                let childAcl = ent.defaultEnvironmentAcl ? this.dataAuthUtils.aclFromTemplate(ent.defaultEnvironmentAcl) : this.dataAuthUtils.aclFrom(ent);
                let childRwd = this.dataAuthProvider.getRoleRwd(childAcl, role);
                if (entBranch.children == undefined)
                    entBranch.children = [];
                (_a = entBranch.children) === null || _a === void 0 ? void 0 : _a.unshift({ text: "(".concat(this._styler.hilite(childRwd), ") ", this._styler.dim("*new enviros*")), value: "*new enviros*" });
            },
            eachEnviro: (envBranch, env, ent, rootMap) => {
                var _a;
                let rwd = this.dataAuthProvider.getRoleRwd(env, role);
                envBranch.text = "(".concat(this._styler.hilite(rwd), ") ", envBranch.text);
                let childAcl = env.defaultCabinetAcl ? this.dataAuthUtils.aclFromTemplate(env.defaultCabinetAcl) : this.dataAuthUtils.aclFrom(env);
                let childRwd = this.dataAuthProvider.getRoleRwd(childAcl, role);
                if (envBranch.children == undefined)
                    envBranch.children = [];
                (_a = envBranch.children) === null || _a === void 0 ? void 0 : _a.unshift({ text: "(".concat(this._styler.hilite(childRwd), ") ", this._styler.dim("*new cabinets*")), value: "*new cabinets*" });
            },
            eachCabinet: (cabBranch, cab, env, ent, rootMap) => {
                let rwd = this.dataAuthProvider.getRoleRwd(cab, role);
                cabBranch.text = "(".concat(this._styler.hilite(rwd), ") ", cabBranch.text);
            },
        };
        return embellisher;
    }
}
exports.default = AuthRoleAllowed;
AuthRoleAllowed.description = 'Renders the privileges granted to an existing Role on each enterprise, environment, and cabinet.';
AuthRoleAllowed.aliases = [];
AuthRoleAllowed.examples = [
    '<%= config.bin %> <%= command.id %> -n deployer',
    '<%= config.bin %> <%= command.id %> --id abc123def456',
    '<%= config.bin %> <%= command.id %> -n deployer -e main'
];
AuthRoleAllowed.flags = {
    id: core_1.Flags.string({ required: false, exclusive: ["name"], description: 'System ID of the Role.' }),
    enterprise: core_1.Flags.string({ char: 'e', required: false, description: '(required only if there are more than one) Name of the Enterprise in which to view the entities to which the role has access.' }),
    // 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." })
};
AuthRoleAllowed.args = {
    name: core_1.Args.string({ required: false, exclusive: ["id"], description: 'Name of the Role.' }),
};
//# sourceMappingURL=allowed.js.map