"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const ops_1 = require("../ops");
const uilogic_1 = require("../uilogic");
const read_stdin_1 = require("../read-stdin");
const command_base_enterprise_1 = require("../command-base-enterprise");
class Login extends command_base_enterprise_1.CommandBaseEnterprise {
    /************ HACK!!! ***********
    * we're disabling this because our api clients fail on some machines.
    * https://github.com/axios/axios/issues/535
    ***********************/
    // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
    // // Read from stdin
    // process.stdin.on('readable', () => {
    //   let chunk;
    //   // Use a loop to make sure we read all available data.
    //   while ((chunk = process.stdin.read()) !== null) {
    //     this.stdinData = (this.stdinData ?? "").concat(chunk);
    //     process.stdout.write(`readable: ${chunk}`);
    //   }
    // });
    // 
    // private stdinData: string | undefined;
    run() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c, _d;
                try {
                    this.bootstrap();
                    const { args, flags } = yield this.parse(Login);
                    if (flags.passwordIn === true)
                        flags.silent = true;
                    if (flags.silent === true) {
                        this.__ui = new ops_1.ThrowingUserInputProvider(this.logger, (flags.tokenOut) ? "suppress" : "write");
                        this.__styler = new ops_1.NoStyleOutputStyler();
                    }
                    let defaultPassword = flags.password;
                    if (flags.passwordIn === true) {
                        defaultPassword = yield (0, read_stdin_1.default)();
                    }
                    if (defaultPassword != undefined)
                        defaultPassword = defaultPassword.trim();
                    let dialoger = new uilogic_1.TenantContextualizer(this.cliEnviro, this._projCfg, this.authClient, this.projCfgRepo, this._ui, this._styler, this.logger);
                    let defaultUserName = (this._userCntx) ? this._userCntx.userName : undefined;
                    defaultUserName = (_a = flags.username) !== null && _a !== void 0 ? _a : defaultUserName;
                    let defaultTenantCode = (_d = (_b = flags.tenantCode) !== null && _b !== void 0 ? _b : (_c = this._projCfg) === null || _c === void 0 ? void 0 : _c.tenantCode) !== null && _d !== void 0 ? _d : this._userCntx.currentTenantCode;
                    this.logger.trace(`Codiac tenant code: ${defaultTenantCode}`);
                    let uctx = yield dialoger.authenticate(defaultTenantCode, defaultUserName, defaultPassword, flags.silent);
                    if (uctx) {
                        if (flags.tokenOut === true && uctx.currentToken) {
                            process.stdout.write(uctx.currentToken);
                        }
                        else {
                            this._ui.userMessage(`Successfully logged in as ${this._styler.hilite(uctx.userName)} ${(uctx.currentTenantCode) ? `[${this._styler.hilite(uctx.currentTenantCode)}]` : ""}`);
                        }
                    }
                    else {
                        if (flags.tokenOut === true) {
                            process.stderr.write("login failed.");
                        }
                        else {
                            this._ui.userMessage("login failed.");
                        }
                    }
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
                finally {
                    yield this.closeConnections();
                }
            }));
        });
    }
}
exports.default = Login;
Login.description = 'Codiac system login to authenticate user under a tenant.';
Login.aliases = ["user:login"];
Login.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    username: core_1.Flags.string({ char: 'u', description: "Username on Codiac" }),
    password: core_1.Flags.string({ char: 'p', description: "password on Codiac" }),
    passwordIn: core_1.Flags.boolean({ char: 'i', exclusive: ["password"], description: "Reads the password directly from the standard input stream.  Enables users to avoid explicitly rendering it in a command string. eg:  `cat mypass.txt | cod login -u joecool --passwordIn`.  Invokes `--silent` mode, so interaction will be disabled." }),
    tenantCode: core_1.Flags.string({ char: 't', description: "Human-readable Identifier for the Codiac tenant to log in under (optional: defaults to the tenant code for the current project or prompts you to select one from your profile)." }),
    tokenOut: core_1.Flags.boolean({ char: 'o', required: false, dependsOn: ["username"], description: "Writes the token as the sole stdout content (so that it is available to be piped or redirected elsewhere, eg `cod login > mycodiactoken.txt`).  Leaves stdout empty on errors.  Invokes `--silent` mode, so interaction will be disabled." }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: ["username", "password"], required: false, description: `(Optional: defaults to false) Prevents interactive user-interface and throws if interaction is needed. Requires arguments: [--username -u, --passwordIn -i]` })
    // useNode: Flags.boolean({ char: 'n', required: false, description: `Replaces ui prompts with node env vars that match the requested prompt` })
};
Login.args = {};
Login.examples = [
    {
        description: "Interactive login",
        command: '<%= config.bin %> <%= command.id %>'
    },
    {
        description: "Scripted login (non-TTY, eg: in a pipeline) with password piped in from an env variable.",
        command: 'echo $PW | <%= config.bin %> <%= command.id %> -u joe.cool@yaml.dev --passwordIn'
    },
    {
        description: "Scripted login to specific tenant (non-TTY, eg: in a pipeline) with password piped in from an env variable.  Use this when the current user is a member of more than one codiac tenant.",
        command: 'echo $PW | <%= config.bin %> <%= command.id %> --tenantCode acme -u joe.cool@yaml.dev --passwordIn'
    },
    {
        description: "Scripted login to specific tenant (non-TTY, eg: in a pipeline) with password read from  an env variable.  Use this when the current user is a member of more than one codiac tenant.",
        command: '<%= config.bin %> <%= command.id %> --tenantCode acme -u joe.cool@yaml.dev --password $PW'
    },
    {
        description: "Login and capture token (with password read from a file) (Non-TTY)",
        command: "cat mypassword.txt | <%= config.bin %> <%= command.id %> -u joe.cool@fyaml.dev --passwordIn --tokenOut"
    },
    {
        description: "Login and capture token (with clear-text password read an env variable) (Non-TTY)",
        command: "<%= config.bin %> <%= command.id %> -u joe.cool@fyaml.dev --password $PW --tokenOut"
    }
];
//# sourceMappingURL=login.js.map