import { Command }    from 'commander';
import prompt         from 'prompt';
import colors         from '@colors/colors/safe';
import SessionManager from '../managers/SessionManager';
import axios          from 'axios';
import HttpManager    from '../managers/HttpManager';
import logger         from '../shared/logging/WinstonLogger';


class CommanderApp {
    program = new Command();

    constructor() {
        this.program
        .name('Dojo CLI')
        .description('CLI for the Dojo application')
        .version('1.0.0Ɑ');

        this.loginCommand();
        this.testSessionCommand();

        this.program.parse();
    }

    loginCommand() {
        this.program.command('login')
        .description('Login into the application')
        .requiredOption('-u, --user <string>', '[Required] Username to use when connecting to server.')
        .option('-p, --password <string>', 'Password to use when connecting to server. If password is not given it\'s asked.')
        .action(async (options) => {
            const passwordPromise = new Promise((resolve, reject) => {
                if ( !options.password ) {
                    prompt.get({
                                   properties: {
                                       password: {
                                           description: colors.cyan('Please enter your password'),
                                           required   : true,
                                           hidden     : true
                                       }
                                   }
                               }, (err, result) => {
                        options.password = result.password;
                        resolve(undefined);
                    });
                } else {
                    resolve(undefined);
                }
            });

            await passwordPromise;

            SessionManager.login(options.user, options.password);
        });
    }

    testSessionCommand() {
        this.program.command('test-session')
        .description('Test availability of session')
        .action(async (options) => {
            const response = await axios.get(HttpManager.TEST_SESSION_URL);

            logger.info('Session is valid');
        });
    }
}


export default CommanderApp;