const moduleDirs = ['src/module', 'vendor/ainias'];
const outputDir = 'public/js/lang';

const fs = require('fs');
var translations = {};

var currentLangs = [];
for (var i = 2, n = process.argv.length; i < n; i++)
{
    currentLangs.push(process.argv[i].split(".")[0]);
}

for (var i = 0, n = moduleDirs.length; i < n; i++) {
    var currentModuleDir = moduleDirs[i];
    var files = fs.readdirSync(currentModuleDir);
    files.forEach(file => {
        if (fs.existsSync(currentModuleDir + "/" + file + "/pwa/translations")) {
            var translationFiles = fs.readdirSync(currentModuleDir + "/" + file + "/pwa/translations");
            translationFiles.forEach(translationFile => {
                var language = translationFile.split('.')[0];
                if (currentLangs.length > 0 && currentLangs.indexOf(language) === -1)
                {
                    return;
                }
                if (typeof translations[language] === 'undefined') {
                    translations[language] = {};
                }
                var res = fs.readFileSync(currentModuleDir + "/" + file + "/pwa/translations/" + translationFile, 'utf8');
                var currentTranslations = JSON.parse(res);
                for (var key in currentTranslations) {
                    translations[language][key] = currentTranslations[key];
                }
            });
        }
    });
}

for (var lang in translations)
{
    // console.log(translations[lang]);
    var langTranslations = JSON.stringify(translations[lang]);
    fs.writeFile(outputDir+"/"+lang+".json", langTranslations, err => {
        if (err){
            throw err;
        }
    });
}