'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, ci } = tools.getArgs();


module.exports.generate = (inputScopes = 'opsys,cc,mywp,sygma,gem,cotg,eac', project) => {

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

  let prj;
  if (project) {
    prj = project;
  } else {
    prj = configUtils.projects.getProject();
  }

  const rootFolder = path.join(process.cwd(), prj.folder);
  const rootSrcFolder = path.join(rootFolder,'src');
  const destFolder = path.join(rootSrcFolder, 'assets/i18n-compiled');
  const globalTranslationsFolder = path.join(rootSrcFolder, 'assets/i18n-global');

  const nmPath = path.join(process.cwd(), 'node_modules');

  var 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'];
  var packages = [];

  var 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 => path.resolve(nmPath,  `${scope}/${pkg}`))
            packages = [...packages, ...files];
          }
      });

      if (!ci) {
        configUtils.packages.getPackages().forEach((pkg) => {
          const localPath = configUtils.packages.getPackagePaths(pkg).root;
          console.log(localPath);
          packages.push(localPath);
        })
      }

      tools.logInfo(`langs: ${langs}`);
      tools.logInfo(`dest folder: ${destFolder}`);
      tools.logInfo(`total packages: ${packages.length}`);
      tools.logInfo(packages.join('\n'));
    })

    .then(() => {
        if (!fs.existsSync(destFolder)) {
          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((pkg) => {
                // console.log('...adding translation from module "' + pkg + '".');
                file = path.join(pkg, `assets/i18n/${lang}.json`);
                addTranslation(file, 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);
                }
            }

            console.log(JSON.stringify(translations, null, 2));

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

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

        tools.logTitle('Post-build assets i18n-compiled folder content:');
        const i18nfiles = tools.getFiles(destFolder);
        console.log(i18nfiles);


        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);
                }
            }
        }
    })
    .catch((e) => {
      throw e;
    });
}
