#! /usr/bin/env node

'use strict'

const fs = require('fs');
const po2json = require('po2json');
const chalk = require('chalk');

const i18nPath = './i18n/'
const srcPath = './src/app/'

const srcFiles = fs.readdirSync(i18nPath);
srcFiles.forEach(function (file, index) {
  const dirPath = `${i18nPath}${file}`;
  const stat = fs.statSync(dirPath)
  if (!stat.isDirectory()) {
    return;
  }
  const dirContents = fs.readdirSync(dirPath);
  const poFiles = dirContents.filter(filename => filename.endsWith('.po'));
  if (poFiles.length) {
    const result = {};
    poFiles.forEach(poFile => {
      const jsonData = po2json.parseFileSync(`${dirPath}/${poFile}`, { format: 'mf' });
      result[poFile.slice(0, -3)] = jsonData;
    });
    const filename = dirToFilename(file);
    fs.writeFile(`${srcPath}${file}/${filename}I18n.ts`, getOutputFileContents(file, result), function(err) {
      if(err) {
          return console.log(`${chalk.default.red(err)}`);
      }
      console.log(`${chalk.default.green('Generated:')} ${chalk.default.yellow(`${filename}I18n.ts`)}`);
    });
  }
});

function getOutputFileContents(file, result) {
  let moduleName = dirToFilename(file);
  moduleName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1);
  return `
export const ${moduleName}I18n = {
${Object.keys(result).map((lang) => {
  return '\t"' + lang + '" : ' + JSON.stringify(result[lang]) + ',\n';
}).join('')
}
}
`
}


function dirToFilename(name) {
  return name.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
}
