"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
const config_ui_utils_1 = require("../../../uilogic/config-ui-utils");
class AuthUserInvite extends command_base_exec_tenant_1.CommandBaseExecTenant {
    constructor() {
        super(...arguments);
        this.adminOnly = true;
    }
    captureArgs() {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(AuthUserInvite);
            let partial = {};
            if (flags.email) {
                partial.email = flags.email;
                partial.login = flags.email;
            }
            if (flags.firstName)
                partial.firstName = flags.firstName;
            if (flags.lastName)
                partial.lastName = flags.lastName;
            partial.roleNames = (_a = flags.role) !== null && _a !== void 0 ? _a : [];
            // ---------------------------------------------------------------
            // TODO: move everything from here down into the base class
            // ---------------------------------------------------------------
            const interactionMode = (this.pipedInput) ? config_ui_utils_1.InteractionModes.silent : (_c = (_b = undefined !== null && undefined !== void 0 ? undefined : (flags.echo ? config_ui_utils_1.InteractionModes.echo : undefined)) !== null && _b !== void 0 ? _b : (flags["to-script"] ? config_ui_utils_1.InteractionModes.toscript : undefined)) !== null && _c !== void 0 ? _c : (flags.silent ? config_ui_utils_1.InteractionModes.silent : undefined);
            const takeDefaults = flags['take-defaults'];
            return [partial, interactionMode, takeDefaults];
        });
    }
    buildCandidate_silently(partial) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if ((partial.email == undefined) || (partial.login == undefined))
                throw new Error("No email provided.");
            if ((partial.firstName == undefined) || (partial.firstName == undefined))
                throw new Error("No firstName provided.");
            if ((partial.lastName == undefined) || (partial.lastName == undefined))
                throw new Error("No lastName provided.");
            let candidate = {
                login: partial.login,
                email: partial.email,
                firstName: partial.firstName,
                lastName: partial.lastName,
                roleNames: (_a = partial.roleNames) !== null && _a !== void 0 ? _a : []
            };
            return candidate;
        });
    }
    buildCandidate_interactively(partial, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.buildCandidate_silently(partial);
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push("--email", candidate.login);
        cmd.push("--firstName", candidate.firstName);
        cmd.push("--lastName", candidate.lastName);
        candidate.roleNames.forEach(r => cmd.push("-r", r));
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                let result = yield this._codiacApi.Auth.AddTenantUser(candidate);
                if (result.error && !_.isEmpty(result.error))
                    throw result.error;
                if (result.success) {
                    this._ui.userMessage(this._styler.colorGood("Success! ").concat((_a = result.message) !== null && _a !== void 0 ? _a : "Invited user"));
                }
                else {
                    this._ui.userMessage((_b = result.message) !== null && _b !== void 0 ? _b : "Failed to invite user (no details given, see log for details)");
                }
                return;
            }
            catch (err) {
                throw err;
            }
        });
    }
}
exports.default = AuthUserInvite;
AuthUserInvite.description = "Adds a user to the current organization. Users must be invited to an organization (*with the exception of the original creator of the organization, who gets automatically added as the administrator*).  NOTE: Users are designated by their email address and can be part of multiple organizations. If the the given email is not yet registered in Codiac, the an invite email will be sent prompting the user to register with Codiac and join the current organziation.  NOTE: Use the `cod auth register` to join yourself.";
AuthUserInvite.examples = [
    '<%= config.bin %> <%= command.id %>',
];
AuthUserInvite.flags = {
    email: core_1.Flags.string({ char: 'e', description: "This will be the user's login/username on Codiac." }),
    firstName: core_1.Flags.string({ char: 'f', description: "(optional; you can edit this later)" }),
    lastName: core_1.Flags.string({ char: 'l', description: "(optional; you can edit this later)" }),
    role: core_1.Flags.string({ char: 'r', multiple: true, description: "Each security role to assign to the user. Use this flag multiple times, once for each role to assign." }),
    // 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." })
};
AuthUserInvite.args = {};
//# sourceMappingURL=invite.js.map