const gettext = require('gettext-parser');
const winston = require('winston');
const { combine, timestamp, printf } = winston.format;
const chalk = require('chalk');
const path = require('path');
const fs = require('fs').promises;

const textDomain = 'alps';
const langRoot = path.resolve(__dirname, '../lang');

const logger = winston.createLogger({
  format: combine(
    timestamp(),
    printf(({ message }) => {
      return message;
    })
  ),
  transports: [
    new winston.transports.Console(),
  ],
});

(async () => {
  logger.info(`📖 Reading the ${chalk.green(`${textDomain}.pot`)} language file from ${chalk.green(langRoot)}`);

  const poContentRaw = await fs.readFile(`${langRoot}/${textDomain}.pot`);
  const poContent = gettext.po.parse(poContentRaw);

  const phpContent = [];
  phpContent.push('<?php');
  phpContent.push('// This file is autogenerated by ALPS. Any modification will be removed after next build.');
  phpContent.push('exit;');
  for (const id of Object.keys(poContent.translations[''])) {
    if (id === '') {
      continue;
    }
    phpContent.push(`__('${id.replace('\'', '\\\'')}', '${textDomain}');`);
  }
  phpContent.push('');

  await fs.writeFile(`${langRoot}/${textDomain}.php`, phpContent.join("\n"));

  logger.info(`✏️ Dump English strings to ${chalk.green(`${langRoot}/${textDomain}.php`)}`);
})().then(() => {
  process.exit(0);
}).catch((err) => {
  console.error(err);
  process.exit(1);
});
