import { Flags } from '@oclif/core';
import BaseCommand from '../lib/baseCommand.js';
import LoginManager from '../lib/loginManager.js';
import PasswordPrompter from '../lib/passwordPrompter.js';
import StatusManager from '../lib/statusManager.js';
export default class Login extends BaseCommand {
    static description = 'Log into the Cloud Script Service';
    static flags = {
        endpoint: Flags.string({ char: 'e', description: 'Endpoint hostname (e.g. customername.skytap-portal.com)' }),
        "password": Flags.string({ char: 'p', description: 'Password' }),
        "password-stdin": Flags.boolean({ char: 'i', description: 'Read password from stdin' }),
        username: Flags.string({ char: 'u', description: 'Username' }),
    };
    async assertPrerequisites() {
        // Login has no prerequisites
    }
    async runImpl() {
        const loginManager = new LoginManager();
        const flagsProvided = Object.keys(this.parsedFlags).length > 0;
        const validPasswordFlagProvided = (this.parsedFlags.password && !this.parsedFlags['password-stdin']) || (!this.parsedFlags.password && this.parsedFlags['password-stdin']);
        const validFlagsProvided = validPasswordFlagProvided && this.parsedFlags.username && this.parsedFlags.endpoint;
        if (flagsProvided && !validFlagsProvided) {
            throw new Error('--endpoint, --username, and either --password or --password-stdin are required');
        }
        let passwd = this.parsedFlags.password;
        if (this.parsedFlags["password-stdin"]) {
            passwd = await PasswordPrompter.prompt("Password:");
        }
        const { endpoint, username } = this.parsedFlags;
        if (endpoint && passwd && username) {
            await loginManager.setCredentials(endpoint, passwd, username);
        }
        await loginManager.login(true);
        StatusManager.finishCommand(`Login as ${loginManager.getUserString()}`);
    }
}
