/**
 * Failed to minify the file using Terser v5.39.0. Serving the original version.
 * Original file: /npm/zoho-extension-toolkit@1.0.27/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
#!/usr/bin/env node

/*
Copyright (c) 2017, ZOHO CORPORATION
License: MIT
*/

var commander = require('commander');
var chalk = require('chalk');
var packageJSON = require('./package.json');
var service = require('./lib/utils/service.js');
var fse = require('fs-extra');
var i18next = require('i18next');
var i18nUtil = require('./lib/i18n/i18n-util.js');
var path = require('path');
var CONST = require('./lib/commands/constants.js');
const pkg = require('./package.json');

const font = require('ansi-colors');
const store = require('./lib/configstore');
const _ = require('./lib/util_modules');

var SUPPORTED_COMMANDS = ['login', 'whoami', 'init', 'pack', 'run', 'cloud_stop', 'cloud_run','validate','list_workspace','pull','push','logout'];
var projectRootDir = process.cwd();
i18nUtil.internationlize();
//let tokenObj = store.get('credential', null);

commander
		.command('login')
		.description(i18next.t("index_login"))
		//.option('--no-localhost', 'login without browser')
		.option('--force', 'force reauthentication')
		.action(function(options) {
			require('./lib/authentication').login(options);
		});
commander
		.command('whoami')
		.description(i18next.t("index_whoami"))
		.action(function() {
			let user = store.get('user');
			let token = store.get('credential');
			//console.log(store.get('oAuthCreatedTime'))
			if (user && token) {
				_.LOGGER.success('Logged as : ' + font.cyan.bold(user.Email));
				if(store.get('default_workspace')){
					_.LOGGER.success('Workspace : ' + font.cyan.bold(store.get('default_workspace')));
				}
			}else{
				_.LOGGER.error(i18next.t("login_error"));
			}
		});

commander
	.command('init')
	.option('--zoho-service <serviceName>', '--project-name <projectName>')
	.description(i18next.t('index_desc'))
	.action(function () {
		require('./lib/commands/init').run(projectRootDir, commander.opts());
	});

commander
	.command('run')
	.description(i18next.t('index_desc_run'))
	.action(function () {
		checkRootDirectory();
		require('./lib/commands/run').run(projectRootDir);
	});

commander
	.command('cloud_run')
	.description(i18next.t("index_cloud_run"))
	.action(function () {
		checkRootDirectory();
		if(service.isZetAPIModelService(projectRootDir)){
			service.sessionExpireCheck().then(()=>{
				require('./lib/commands/cloud_run').run(projectRootDir);
			});
		}else{
			_.LOGGER.message('Command ' + font.underline.bold('ZET cloud_run') +' not applicable for the selected service as it is not mapped to ZET online model.');
		 }
	});

commander
	.command('cloud_stop')
	.description(i18next.t("index_cloud_stop"))
	.action(function () {
		checkRootDirectory();
		if(service.isZetAPIModelService(projectRootDir)){
			service.sessionExpireCheck().then(()=>{
				require('./lib/commands/cloud_run').stop(projectRootDir);
			});
		}else{
			_.LOGGER.message('Command ' + font.underline.bold('ZET cloud_stop') +' not applicable for the selected service as it is not mapped to ZET online model.');
		 }
	});

commander
	.command('validate')
	.description(i18next.t('index_desc_validate'))
	.action(function () {
		checkRootDirectory();
		//&& !_.JS.isNull(tokenObj)
		if(service.isZetAPIModelService(projectRootDir) ){
			service.sessionExpireCheck().then(()=>{
				require('./lib/commands/validation_api').run(projectRootDir);
			});
		}else{
			var ruleConfig = service.getValidationRules(projectRootDir);
			var isValid = require('./lib/commands/validate').run(projectRootDir, ruleConfig.PRE_RULES);
			if (isValid) {
				console.log(chalk.bold.green(i18next.t("index_validate_sucess")));
			}
		}
	});


commander
	.command('pack')
	.description(i18next.t('index_desc_pack'))
	.action(function () {
		checkRootDirectory();
		// && !_.JS.isNull(tokenObj)
		if(service.isZetAPIModelService(projectRootDir)){
			service.sessionExpireCheck().then(()=>{
				require('./lib/commands/validation_api').run(projectRootDir);
			});
		}else{
			require('./lib/commands/package').run(projectRootDir);
		}
	});

commander
	.command('pull')
	.description(i18next.t("index_pull"))
	.action(function () {
		service.sessionExpireCheck().then(()=>{
			require('./lib/commands/pull_app').run(projectRootDir);	
		});
	});

commander
	.command('list_workspace')
	.description(i18next.t("index_list_workspace"))
	.action(function () {
		service.sessionExpireCheck().then(()=>{
			require('./lib/commands/get_workspace').run()
			.catch((error) => {
				_.LOGGER.debug('Error: ' + error);
			});
		});
	});

commander
	.command('push')
	.description(i18next.t("index_push"))
	.action(function () {
		checkRootDirectory();
		if(service.isZetAPIModelService(projectRootDir)){
			//auto logout if the session expires
			service.sessionExpireCheck().then(()=>{
				require('./lib/commands/update_app').run(projectRootDir);
			});
		 }else{
			_.LOGGER.message('Command ' + font.underline.bold('ZET push') +' not applicable for the selected service as it is not mapped to ZET online model.');
		 }
	});

commander
	.command('logout')
	.description(i18next.t("index_logout"))
	.action(function() {
		require('./lib/authentication').logout();
	});	

commander
	.option("-v, --version", i18next.t('index_version'))

// commander
// 	.option("-h, --help", i18next.t('index_help'))
	
commander
	.option(" --force", i18next.t('index_login_force'))

commander
	.option(" --zoho-service <serviceName>", 'Name of the Zoho service')	

commander
	.option(" --project-name <projectName>", 'Name of the Project')	

try {
	//for checking the version
	(async () => {
  		const { default: updateNotifier } = await import('update-notifier');
  		updateNotifier({ 
		pkg: pkg,
        updateCheckInterval: 1000 * 60 * 60 * 24 
		}).notify({ defer: false, isGlobal: true });
	})();
	/* For -v version fix */
	var processArg = process.argv;
	if (processArg.indexOf("-v") > -1 || processArg.indexOf("--version") > -1) {
		console.log(packageJSON.version);
		return;
	}

	commander.parse(process.argv);
	var commandArgs = process.argv.length > 2 ? process.argv.slice(2) : [];
	var showHelp = commander.args.length == 0 || (commandArgs.length >= 1 && SUPPORTED_COMMANDS.indexOf(commandArgs[0]) === -1);
	
	if (showHelp) {
		commander.help();
	}

} catch (err) {
	_.LOGGER.error((chalk.bold.red(i18next.t('index_err'), err.stack)));
}

function checkRootDirectory() {
	var manifestFile = path.join(projectRootDir, CONST.PLUGIN_MANIFEST);
	if (!fse.existsSync(manifestFile)) {
		_.LOGGER.error((chalk.bold.red(i18next.t('index_ntindir'))));
		process.exit(1);
	}
	//Invalid manifest json
	try {
		fse.readJsonSync(manifestFile);
	} catch (err) {
		_.LOGGER.error((chalk.bold.red(i18next.t('index_invalid'))));
		process.exit(1);
	}
	//"json-dup-key-validator": "^1.0.3"
	// try {
	// 	var data = jsonValidator.parse(fs.readFileSync(jsonPath, 'utf8'), false);
	// } catch(e) {
	// 	_.LOGGER.error((chalk.bold.red(i18next.t('index_invalid'))));
	// 	process.exit(1);
	// }
}