'use strict';

// GLOBAL
const path = require('path');
const fs = require('fs');
const extend = require('extend');

// LOCAL
const tools = require('../../tools');
const configUtils = require('../../../csdr/config/config-utils');

// FETCH ARGS
const { dryRun, scopes } = tools.getArgs();


module.exports.generate = (inputScopes = '', inputPkg) => {

  tools.logTitle('Generating translations...');

  let pkg = inputPkg;
  if (!pkg) {
    pkg = configUtils.packages.getPackage();
  }

  const rootFolder = pkg.paths.root;
  const rootSrcFolder = path.join(rootFolder,'src');
  const destFolder = path.join(rootSrcFolder, 'assets/i18n-compiled');
  const globalTranslationsFolder = path.join(rootSrcFolder, 'assets/i18n-global');

  let nmPath = pkg.paths.repoNodeModules;

  let langs = ['en', 'fr'];
  if (pkg.build && pkg.build.translationLanguages) {
    if (pkg.build.translationLanguages === 'ALL') {
      langs = ['bg', 'es', 'cs', 'da', 'de', 'et', 'el', 'en', 'fr', 'ga', 'hr', 'it', 'lv', 'lt', 'hu', 'mt', 'nl', 'pl', 'pt', 'ro', 'sk', 'sl', 'fi', 'sv'];
    } else {
      langs = pkg.build.translationLanguages;
    }
  }
  let packages = [];

  let genScopes;
  if (scopes) {
    genScopes = scopes;
  } else {
    genScopes = inputScopes;
  }

  var translations = {};


  return Promise.resolve()
    .then(() => {
      tools.logInfo('Getting scopes packages');
      genScopes = genScopes.split(',').map(s => '@' + s);

      genScopes.forEach((scope) => {
          tools.logInfo(`Adding packages from scope "${scope}"`);
          const scopePath = path.resolve(nmPath, scope);
          if (tools.isDirExists(scopePath)) {
            let files = fs.readdirSync(scopePath).map((pkg) => {
              return {
                name: pkg,
                scope: scope,
                folder: path.resolve(nmPath,  `${scope}/${pkg}`)
              }
            });
            packages = [...packages, ...files];
          }
      });

      tools.logInfo(`langs: ${langs}`);
      tools.logInfo(`dest folder: ${destFolder}`);
      tools.logInfo(`total packages: ${packages.length}`);
      tools.logInfo(JSON.stringify(packages, null, 1));
    })

    .then(() => {
        if (!fs.existsSync(destFolder) && !dryRun) {
          fs.mkdirSync(destFolder);
        }

        langs.forEach((lang) => {
            tools.logInfo(`Building translation for lang: "${lang}"`);

            // Add global translations
            let file = path.join(globalTranslationsFolder, `${lang}.json`);
            addTranslation(file, lang);

            // Add module translations
            packages.forEach((pkgDeps) => {
                let baseI18nPath = 'i18n';
                if (pkgDeps.scope === '@eui') {
                  baseI18nPath = 'i18n-eui';

                  processTranslationsFolder(pkgDeps, baseI18nPath, lang);

                  // process additional translation folders if set as option in config
                  if (pkg.build && pkg.build.translationAdditionalFolders) {
                    processTranslationsFolder(pkgDeps, pkg.build.translationAdditionalFolders, lang);
                  }

                  baseI18nPath = 'i18n-ecl';

                  processTranslationsFolder(pkgDeps, baseI18nPath, lang);

                  // process additional translation folders if set as option in config
                  if (pkg.build && pkg.build.translationAdditionalFolders) {
                    processTranslationsFolder(pkgDeps, pkg.build.translationAdditionalFolders, lang);
                  }

                } else {
                  processTranslationsFolder(pkgDeps, baseI18nPath, lang);

                  // process additional translation folders if set as option in config
                  if (pkg.build && pkg.build.translationAdditionalFolders) {
                    processTranslationsFolder(pkgDeps, pkg.build.translationAdditionalFolders, lang);
                  }
                }

            });

            // Write final file
            if ({}.hasOwnProperty.call(translations, lang)) {
                const dest = path.join(destFolder, `${lang}.json`);
                const data = JSON.stringify(translations[lang]);

                if (!dryRun) {
                  fs.writeFileSync(dest, data);
                }
            }

            tools.logSuccess('Translation for lang ' + lang + ' done.');
        });

        tools.logSuccess('All translations files generated.');


        function addTranslation(file, lang) {
            if (fs.existsSync(file)) {
                let data = fs.readFileSync(file, 'utf-8');
                try {
                    data = JSON.parse(data);
                    translations[lang] = extend({}, translations[lang], data);
                } catch(e) {
                    console.log('Error parsing lang JSON', file);
                    console.log(e);
                }
            }
        }

        function processTranslationsFolder(pkg, folder, lang) {
          tools.logInfo(`------>Scanning ${folder}`);

          let file = path.join(pkg.folder, `assets/${folder}/${lang}.json`);

          tools.logInfo(`Adding translations from ${pkg.folder}`);
          if (tools.isFileExists(file)) {
            tools.logInfo(`${file} found...adding`);
            addTranslation(file, lang)
          } else {
            file = path.join(pkg.folder, `assets/i18n/${lang}.json`);
            if (tools.isFileExists(file)) {
              tools.logInfo(`${file} found...adding`);
              addTranslation(file, lang)
            } else {
              tools.logInfo(`${file} not found...skipping`);
            }
          }
        }
    })
    .catch((e) => {
      throw e;
    });
}
