var fs = require('fs');
var path = require('path');
var Parser = require('i18next-scanner').Parser;

var directoryPaths = ['src/pages', 'src/components'];

var zhHandler = function (key) {
  zhParser.set(key, key);
};

var enHandler = function (key) {
  var defaultValue = '__TRANSLATION__';
  enParser.set(key, defaultValue);
};

var zhParser = new Parser();
var enParser = new Parser();

function processDirectory(directoryPath) {
  const files = fs.readdirSync(directoryPath);

  for (let file of files) {
    let fullPath = path.join(directoryPath, file);

    if (fs.statSync(fullPath).isDirectory()) {
      processDirectory(fullPath);
    } else {
      let content = fs.readFileSync(fullPath, 'utf-8');

      zhParser.parseFuncFromString(content, { list: ['t'] }, zhHandler);
      enParser.parseFuncFromString(content, { list: ['t'] }, enHandler);
    }
  }
}

// Process all directories
for (let directoryPath of directoryPaths) {
  processDirectory(directoryPath);
}

var zhTranslations = zhParser.get({ sort: true });
var enTranslations = enParser.get({ sort: true });

// 写入翻译到目标json文件
fs.writeFileSync(
  'src/i18n/zh.json',
  JSON.stringify(zhTranslations.en.translation, null, 2),
);

// fs.writeFileSync(
//   'src/i18n/en.json',
//   JSON.stringify(enTranslations.en.translation, null, 2),
// );

var fileTranslations = Object.keys(zhTranslations.en.translation).length;
console.log('✅ 翻译查找完成，共找到 ' + fileTranslations + ' 个翻译项');
