'use strict';

const tools = require('../../utils/tools');
const https = require('https');
var fs = require('fs');
const { filePath, sourceLang, targetLang } = require('../tools').getArgs();
const TEXT = '<text>';
const TEXT_END = '</text>';
const CONTENT = '<content>';
const CONTENT_END = '</content>';

// example: node translate-utils.js --filePath c:\i18n\en.json --sourceLang en --targetLang bg

const readFile = (filePath) => {
    return JSON.parse(fs.readFileSync(filePath));
}

const translate = (text, sourceLang, targetLang) => {
    tools.logTitle(`Translating file : ${filePath} from ${sourceLang} to ${targetLang}.`);
    return new Promise((resolve, reject) => {
        const data = JSON.stringify({
            textToTranslate: text,
            sourceLanguage: sourceLang,
            targetLanguage: targetLang
        });

        const options = {
            hostname: 'europa.eu',
            path: '/webtools/rest/etrans/translate',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': data.length
            }
        };

        const req = https.request(options, res => {
            let chunks_of_data = [];

            res.on('data', d => {
                chunks_of_data.push(d);
            });
            res.on('end', () => {
                tools.logInfo('Received response from eTrans service.');
                let response_body = Buffer.concat(chunks_of_data);
                var response = JSON.parse(response_body);
                resolve(Buffer.from(response.translation, 'base64').toString());
            });
        });

        req.on('error', error => {
            reject(error);
            return;
        });

        tools.logInfo('Sending request to eTrans service.');
        req.write(data);
        req.end();
    });
}

const  prepareStringToTranslate = (arrLines, result) => {
    var keys = Object.keys(arrLines);
    keys.forEach((key) => {
        if (arrLines[key] instanceof Object && !(arrLines[key] instanceof Array)) {
            result += prepareStringToTranslate(arrLines[key], '');
        } else {
            result += `${TEXT}${arrLines[key]}${TEXT_END}`;
        }
    });
    return result;
}

const  createResultJsonFile = (arrLines, res) => {
    const resString = res.split(`${CONTENT}${TEXT}`).pop().split(`${TEXT_END}${CONTENT_END}`)[0];
    const resArr = resString.split(`${TEXT_END}${TEXT}`);
    var resultJson = Object.assign({}, arrLines);
    var finalRes = iterateResultToJson(resultJson, resArr);
    return finalRes;
}

const iterateResultToJson = (resultJson, resArr) => {
    var keys = Object.keys(resultJson);
    keys.forEach((key, index) => {
        if (resultJson[key] instanceof Object && !(resultJson[key] instanceof Array)) { // If there is nested JSON
            resultJson[key] = iterateResultToJson(resultJson[key], resArr.slice(index));
            var subKeys = Object.keys(resultJson[key]);
            resArr.splice(index, subKeys.length - 1); // remove elements for nested JSON from results array
        } else {
            if (resultJson[key] instanceof Array) {
                resultJson[key] = resArr[index].split(',').map(el => el.trim());
            } else {
                resultJson[key] = resArr[index];
            }
        }
    });
    return resultJson;
}

const translateI18nFile = () => {
    return Promise.resolve()
        .then(() => {
            const arrLines = readFile(filePath);
            const destFolder = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
            var stringToTranslate = prepareStringToTranslate(arrLines, '');
            translate(`${CONTENT}${stringToTranslate}${CONTENT_END}`, sourceLang, targetLang)
                .then((res) => {
                    const resultJson = createResultJsonFile(arrLines, res);
                    fs.writeFile(`${destFolder}${targetLang}.json`, JSON.stringify(resultJson, null, 2), function (err) {
                        if (err)  { tools.logError(err); }
                        tools.logInfo(`File ${targetLang}.json created.`);
                    });

                }, (err) => {
                    tools.logInfo(`Error: ${err}`);
                });
        }).catch((error) => {
            tools.logError(error);
          });
}

translateI18nFile();

module.exports.translateI18nFile = translateI18nFile;