#!/usr/bin/env node

'use strict';
const config = require('./config');

const Auth = require('../lib/Auth');
const API = require('../lib/API');
const SSHC = require('./SSHC');
const Helps = require('./Helps');

const chalk = require('chalk');
const { argv } = require('yargs')

const argvRaw = process.argv.slice(2);

process.on('uncaughtException', function (err) {
	// console.debug('Uncaught exception -',err.stack || err)
	process.exit(0)
})
process.on('unhandledRejection', function (err) {
	// console.debug('Unhandled Rejection -', err.stack || err);
	process.exit(0)
});

const cli = Helps.help();

(async () => {

	// if (argvRaw.indexOf('--test') > -1) {
	// 	console.log(await Auth.profile());
	// 	process.exit(0);
	// }

	if (argvRaw.indexOf('--purge') > -1) {
		await SSHC.purge();
		process.exit(0);
	}

	// if (argvRaw.indexOf('--debug') > -1) {
	// 	await SSHC.debug();
	// 	process.exit(0);
	// }

	if(!await API.checkConnection()) {
		console.log(chalk.magenta(`Conexão com o servidor falhou, tente novamente.`));
		process.exit(1);
	}

	if (argvRaw.indexOf('--validate') > -1 && config.has('tokenData')) {
		await SSHC.validate();
		process.exit(0);
	}

	if (argvRaw.indexOf('--refresh') > -1 && config.has('tokenData')) {
		await SSHC.refresh();
		process.exit(0);
	}

	if (argvRaw.indexOf('--register') > -1) {
		await SSHC.register();
		process.exit(0);
	}

	if (argvRaw.indexOf('--rlogin') > -1) {
		await SSHC.relogin();
		process.exit(0);
	}

	if (argvRaw.indexOf('--login') > -1) {
		await SSHC.login();
		process.exit(0);
	}

	if (argvRaw.indexOf('--logout') > -1) {
		await SSHC.logout();
		process.exit(0);
	}

	if(!config.has('tokenData')) {
		console.log(`\n
		${chalk.cyan.bold(`Você não esta logado! Use 'sshc --login' para efetuar o login.`)}
		${chalk.magenta.bold(`Se não tiver um cadastro use 'sshc --register' para criar um cadastro.`)}
		\n`);
		process.exit(0);
	}

	if(!Auth.sessionTimeIsValid()) {
		try {
			let newSession = await Auth.refreshSession(true);
			if(newSession != true && newSession.data) {
				config.delete('tokenData');
				config.set('tokenData', newSession.data);
			}
		} catch(err) {
			console.log(chalk.red(`Ocorreu um erro ao renovar sessão!`));
			console.log(chalk.green(`Faça o login novemente para continuar`));
			await SSHC.relogin();
		}
	}

	if (argvRaw.indexOf('--mfa') > -1) {
		await SSHC.statusMFA();
		process.exit(0);
	}

	if (argvRaw.indexOf('--enable-mfa') > -1) {
		await SSHC.enableMFA();
		process.exit(0);
	}

	if (argvRaw.indexOf('--disable-mfa') > -1) {
		await SSHC.disableMFA();
		process.exit(0);
	}

	if (argvRaw.indexOf('--phone') > -1) {
		await SSHC.registerPhoneNumber(argv);
		process.exit(0);
	}

	if (argvRaw.indexOf('--remove-phone') > -1) {
		await SSHC.removePhoneNumber();
		process.exit(0);
	}

	if(argvRaw.length == 0) {
		cli.showHelp();
		process.exit(0);
	}

	// console.log(argvRaw, argv);

	if(argvRaw[0].startsWith('server')) {
		const action = argvRaw[1] || false;

		switch(action) {
			case 'add':
				await SSHC.serverAdd(argv);
				break;

			case 'form':
				await SSHC.serverAddWithForm(argv);
				break;

			case 'delete':
			case 'del':
			case 'rm':
				await SSHC.serverDelete(argv);
				break;

			case 'list':
			case 'ls':
				await SSHC.serverList(argv);
				break;

			case 'help':
			default:
				Helps.serverUsage().showHelp();
		}
		process.exit(0);
	}
	else if(argvRaw[0].startsWith('key')) {
		const action = argvRaw[1] || false;

		switch(action) {
			case 'link':
				await SSHC.keyLink(argv);
				break;
			case 'unlink':
				await SSHC.keyUnlink(argv);
				break;
			
			case 'add':
				await SSHC.keyAdd(argv);
				break;

			case 'delete':
			case 'del':
			case 'rm':
				await SSHC.keyDelete(argv);
				break;

			case 'list':
			case 'ls':
				await SSHC.keyList(argv);
				break;

			case 'import':
				await SSHC.keyImport(argv);
				break;

			case 'help':
			default:
				Helps.keysUsage().showHelp();
		}
		process.exit(0);
	}
	else if(argvRaw[0].startsWith('group')) {
		const action = argvRaw[1] || false;

		switch(action) {
			case 'link':
				await SSHC.groupLink(argv);
				break;
			
			case 'unlink':
				await SSHC.groupUnlink(argv);
				break;
			
			case 'add':
				await SSHC.groupAdd(argv);
				break;

			case 'delete':
			case 'del':
			case 'rm':
				await SSHC.groupDelete(argv);
				break;

			case 'list':
			case 'ls':
				await SSHC.groupList(argv);
				break;

			case 'help':
			default:
				Helps.groupsUsage().showHelp();
		}
		process.exit(0);
	}

	await SSHC.connect(argv);
})();
