#!/usr/bin/env node
/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * npm install --save-dev colors
 * npm install --save-dev iconv-lite
 */

'use strict';

require('colors');
const fs = require('fs-extra');
const readline = require('readline');

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});

const client_id = 'J2f4lmfl2XghGb92zQ4N';
const client_secret = '1qHQ9YQNMc';

function translate(query, target) {
	return new Promise((resolve) => {
		if (target !== 'ko') {
			var api_url = 'https://openapi.naver.com/v1/papago/n2mt';
			var request = require('request');
			var options = {
				url: api_url,
				form: { source: 'ko', target: target, text: query },
				headers: { 'X-Naver-Client-Id': client_id, 'X-Naver-Client-Secret': client_secret },
			};
			request.post(options, function (error, response, body) {
				if (!error && response.statusCode == 200) {
					resolve(JSON.parse(body).message.result.translatedText.trim());
				} else {
					resolve(query.trim());
				}
			});
		} else {
			resolve(query.trim());
		}
	});
}

function showLogo(callBack) {
	fs.readFile('./banner.txt', 'utf8', (error, jsonFile) => {
		const logo = jsonFile;
		fs.readFile('./package.json', 'utf8', (error, jsonFile) => {
			const packageInfo = JSON.parse(jsonFile);
			console.log(logo.green + '\n' + (packageInfo.description + ' ' + packageInfo.version).red);
			callBack();
		});
	});
}

var myArgs = process.argv.slice(2);

function translateQ(translateQueue, target, callBack ) {
	const q = translateQueue.shift();
	if (q !== null && q !== undefined) {
		translate(q.query, target).then((result) => {
			process.stdout.write(".");
			q.setter(result);
			translateQ(translateQueue, target, callBack );
		});
	} else {
		callBack();
	}
}

showLogo(() => {
    if (myArgs.length > 0) {
        const folderName = myArgs[0];
		const question = [];
		question.push('Select Language to Translate.)');
		question.push('ko - Korean(Resort)');
		question.push('ja - Japanese');
		question.push('en - English');
		question.push('cn - Chinese');
		question.push('es, fr, vi, th, id');
		question.push('Language (ja | en | cn ...) - ? ');
		rl.question(question.join('\n'), function (locale = '') {
			let target = 'en';
			switch (locale.toLowerCase()) {
				case 'ko':
				case 'korean':
					target = 'ko';
					break;
				case 'ja':
				case 'japanese':
					target = 'ja';
					break;
				case 'en':
				case 'english':
					target = 'en';
					break;
				case 'cn':
				case 'zh':
				case 'zh-cn':
				case 'chinese':
					target = 'zh-CN';
					break;
				case 'es':
				case 'fr':
				case 'vi':
				case 'th':
				case 'id':
					target = locale.toLowerCase();
					break;
			}
			console.log("Translate Korean to " + target.red + " start !!");
			fs.readFile(folderName + '.json', 'utf-8', function (err, jsonFile) {
				const jsonInfo = JSON.parse(jsonFile);
				const translateQueue = [];
				const keys = Object.keys(jsonInfo);
				keys.forEach(key => {
					if (typeof(jsonInfo[key]) === 'string') {
						translateQueue.push({ query : jsonInfo[key], setter : (txt) => {
							jsonInfo[key] = txt;
						}})
					} else if (typeof(jsonInfo[key]) === 'object') {
						const childObj = jsonInfo[key];
						const childKeys = Object.keys(childObj);
						childKeys.forEach(childKey => {
							if (typeof(childObj[childKey]) === 'string') {
								translateQueue.push({ query : childObj[childKey], setter : (txt) => {
									childObj[childKey] = txt;
								}})
							}
						});
					}
				});
				translateQ(translateQueue, target, function() {
					fs.writeFile(
						folderName + '-' + target + '.json',
						JSON.stringify(jsonInfo, null, "\t"),
						'utf-8',
						() => {
							console.log("\n\nTranslate Korean to " + target.red + " end !! - " + folderName + '-' + target + '.json');
							process.exit(1);
						}
					);
				});
			});
		});
	} else {
        console.log('missing argument!!'.red + ' ex) node ./scripts/translate.js docs/translate');
		process.exit(1);
	}
});

