const fs = require("fs");
const path = require("path");

const { mergeDeepLeft } = require("ramda");

const packageDir = path.join(__dirname, "../../../");

const getPkgTransPath = pkg => {
  const basePath = path.join(packageDir, pkg);

  const transPath1 = path.join(basePath, "app/javascript/src/translations");
  const transPath2 = path.join(basePath, "src/translations");

  return fs.existsSync(transPath1) ? transPath1 : transPath2;
};

const packages = fs.readdirSync(packageDir);

const loadTranslations = translationsDir => {
  try {
    const jsonFiles = fs
      .readdirSync(translationsDir)
      .filter(file => file.endsWith(".json"))
      .map(file => path.join(translationsDir, file));

    const translations = {};

    jsonFiles.forEach(jsonFile => {
      const content = fs.readFileSync(jsonFile, "utf8");
      const basename = path.basename(jsonFile, ".json");

      translations[basename] = { translation: JSON.parse(content) };
    });

    return translations;
  } catch {
    return {};
  }
};

const packageTranslations = packages
  .map(pkg => loadTranslations(getPkgTransPath(pkg)))
  .reduce(mergeDeepLeft);

module.exports = packageTranslations;
