"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrivilegeAbbrevsEnum = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const config_ui_utils_1 = require("../../../uilogic/config-ui-utils");
const contracts_1 = require("../../../apis/codiac-api/contracts");
const command_base_exec_1 = require("../../../command-base-exec");
const type_safety_utils_1 = require("../../../uilogic/type-safety-utils");
var PrivilegeAbbrevsEnum;
(function (PrivilegeAbbrevsEnum) {
    PrivilegeAbbrevsEnum["modify"] = "modify";
    PrivilegeAbbrevsEnum["read"] = "read";
    PrivilegeAbbrevsEnum["none"] = "none";
})(PrivilegeAbbrevsEnum = exports.PrivilegeAbbrevsEnum || (exports.PrivilegeAbbrevsEnum = {}));
class AuthEnvironmentAllow 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(AuthEnvironmentAllow);
            let partial = {};
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            if (flags.environment)
                partial.environment = flags.environment;
            if (flags.role)
                partial.role = flags.role;
            if (flags.privilege) {
                partial.privilege = type_safety_utils_1.TypeSafetyUtils.toEnum(PrivilegeAbbrevsEnum, flags.privilege);
                switch (flags.privilege) {
                    case PrivilegeAbbrevsEnum.modify:
                        partial.privileges = [contracts_1.Privilege.create, contracts_1.Privilege.read, contracts_1.Privilege.update, contracts_1.Privilege.delete];
                        break;
                    case PrivilegeAbbrevsEnum.read:
                        partial.privileges = [contracts_1.Privilege.read];
                        break;
                    case PrivilegeAbbrevsEnum.none:
                    default:
                        partial.privileges = [];
                        break;
                }
            }
            // ---------------------------------------------------------------
            // 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.enterprise == undefined || _.isEmpty(partial.enterprise))
                throw new Error("Must specify enterprise.");
            if (partial.environment == undefined || _.isEmpty(partial.environment))
                throw new Error("Must specify environment.");
            if (partial.role == undefined || _.isEmpty(partial.role))
                throw new Error("Must specify role.");
            if (partial.privilege == undefined || _.isEmpty(partial.privilege))
                throw new Error("Must specify privilege.");
            if (partial.privileges == undefined)
                throw new Error("Must specify privileges.");
            let candidate = {
                /* cmd arg */ enterprise: partial.enterprise,
                /* cmd arg */ environment: partial.environment,
                /* cmd arg */ privilege: partial.privilege,
                role: partial.role,
                /* api syntax */ privileges: partial.privileges,
                /* api syntax */ entityType: "Environment",
                /* api syntax */ entityKey: { enterpriseCode: partial.enterprise, code: partial.environment }
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // TODO: 
            // 1) select an enterprise (if > 1)
            // 2) select a role (render already assigned w rwx or read/modify)
            // 3) multi-select privileges (w existing pre-selected)
            return yield this.buildCandidate_silently(partial, rootMap);
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--enterprise", candidate.enterprise);
        cmd.push("--environment", candidate.environment);
        cmd.push("--role", candidate.role);
        cmd.push("--privilege", candidate.privilege);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // throw new Error("Auth.setEntityPermission not yet implemented on api");
            const req = {
                entityType: candidate.entityType,
                entityKey: candidate.entityKey,
                role: candidate.role,
                privileges: candidate.privileges,
                comprehensive: true
            };
            let result = yield this._codiacApi.Auth.SetEntityPermission(req);
            if (result.error)
                throw result.error;
            if (result.success) {
                this._ui.userMessage(this._styler.colorGood("Success! ").concat((_a = result.message) !== null && _a !== void 0 ? _a : "Assigned permissions."));
            }
            else {
                this._ui.userMessage((_b = result.message) !== null && _b !== void 0 ? _b : "Failed to assign permissions (no details given, see log for details)");
            }
            return;
        });
    }
}
exports.default = AuthEnvironmentAllow;
AuthEnvironmentAllow.description = 'Sets permissions for a security Role on the given environment entity. (NOT additive: this command overwrites any existing permissions set for this role on the entity).';
AuthEnvironmentAllow.aliases = ["auth:enviro:allow"];
AuthEnvironmentAllow.examples = [
    '<%= config.bin %> <%= command.id %> --enteprise main --environment dev --role developer --privilege modify',
    '<%= config.bin %> <%= command.id %> -e prod -r developer -p none',
    '<%= config.bin %> <%= command.id %> -e qa -r productmanager -p read'
];
AuthEnvironmentAllow.flags = {
    enterprise: core_1.Flags.string({ required: false, description: 'Name of the Enterprise containing the environemnt. (Required only if more than one exists).' }),
    environment: core_1.Flags.string({ char: 'e', required: false, description: 'Name of the Environment being protected. Required in silent mode.' }),
    role: core_1.Flags.string({ char: 'r', required: false, description: 'Name of the Role being assigned. Required in silent mode.' }),
    privilege: core_1.Flags.string({ char: 'p', required: true, options: Object.keys(PrivilegeAbbrevsEnum), description: 'The permission to assign to the Role. ("modify" infers permission to create, read, update, and delete.  "none" removes any permissions set for the role)' }),
    // 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." })
};
AuthEnvironmentAllow.args = {};
//# sourceMappingURL=allow.js.map