import * as fs from 'fs';
import axios from 'axios';
// @ts-ignore
import * as xliff from 'xliff';

// import { TranslateMessageFormatCompiler } from 'ngx-translate-messageformat-compiler';

function flatten(data: any) {
    const result: any = {};

    function recurse(cur: any, prop: any) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
            let l = 0;
            for (let i = 0, l = cur.length; i < l; i++) recurse(cur[i], prop + '[' + i + ']');
            if (l === 0) result[prop] = [];
        } else {
            let isEmpty = true;
            for (const p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop + '.' + p : p);
            }
            if (isEmpty && prop) result[prop] = {};
        }
    }

    recurse(data, '');
    return result;
}

function unflatten(data: any) {
    if (Object(data) !== data || Array.isArray(data)) return data;
    const regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder: any = {};
    for (const p in data) {
        let cur: any = resultholder,
            prop = '',
            m: any;
        while ((m = regex.exec(p))) {
            cur = cur[prop] || (cur[prop] = m[2] ? [] : {});
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[''] || resultholder;
}

async function execute() {
    // const flatGerman = JSON.parse(fs.readFileSync('de-flat.json', 'utf-8'));

    const german = JSON.parse(fs.readFileSync('./../../apps/red-ui/src/assets/i18n/de.json', 'utf-8'));
    const flatGerman = flatten(german);

    const english = JSON.parse(fs.readFileSync('./../../apps/red-ui/src/assets/i18n/en.json', 'utf-8'));

    const flatEnglish = flatten(english);

    const apiKey = 'AIzaSyBiqNTundSKFjAJnSb4wSVLDU6w0Kv651M';

    // const tmfc = new TranslateMessageFormatCompiler();

    for (const key of Object.keys(flatEnglish)) {
        if (!flatGerman[key]) {
            const value = flatEnglish[key];
            const apiUrl = `https://www.googleapis.com/language/translate/v2?key=${apiKey}&q=${value}&source=en&target=de`;

            const response = await axios.get(apiUrl);
            let translated = flatEnglish[key];
            try {
                translated = response.data.data.translations[0].translatedText;
            } catch (e) {}
            console.log('missing: ' + key + ' -> ' + flatEnglish[key] + ' -> ' + translated);
            flatGerman[key] = translated;
        }
    }

    for (let key of Object.keys(flatGerman)) {
        if (!flatEnglish[key]) {
            delete flatGerman[key];
        }
    }

    for (let key of Object.keys(flatGerman)) {
        try {
            //   const result = tmfc.compile(flatGerman[key], 'de');
            //   console.log(result);
        } catch (e) {
            console.error('ERROR AT: ', flatGerman[key]);
        }
    }

    for (let key of Object.keys(flatEnglish)) {
        try {
            //   const result = tmfc.compile(flatEnglish[key], 'de');
            //   console.log(result);
        } catch (e) {
            console.error('ERROR AT: ', flatEnglish[key]);
        }
    }

    const mergedGerman = { ...flatEnglish, ...flatGerman };

    const finalGerman = unflatten(mergedGerman);

    fs.writeFileSync('./../../apps/red-ui/src/assets/i18n/de.json', JSON.stringify(finalGerman));

    const js: any = {
        resources: {
            redaction: {},
        },
        sourceLanguage: 'en-US',
        targetLanguage: 'de-DE',
    };

    for (const key of Object.keys(flatEnglish)) {
        js.resources.redaction[`${key}`] = {
            source: flatEnglish[`${key}`],
            target: flatGerman[`${key}`],
        };
    }

    xliff.jsToXliff12(js, (err: any, res: any) => {
        fs.writeFileSync('./redaction-en-to-de.xliff', res);
    });

    const xliffImport = fs.readFileSync('./import.xliff', 'utf-8');
    xliff.xliff12ToJs(xliffImport, (err: any, res: any) => {
        const ns = res.resources.redaction;

        const importGerman: any = {};
        const importEnglish: any = {};

        for (let key of Object.keys(ns)) {
            importGerman[key] = ns[key].target;
            importEnglish[key] = ns[key].source;
        }

        const importReadyEnglish = unflatten(importEnglish);
        const importReadyGerman = unflatten(importGerman);

        console.log(importReadyEnglish);
        console.log(importReadyGerman);
    });
}

execute().then();
