#! /usr/bin/env node

'use strict'

const fs = require('fs');
const sh = require('shelljs');
const rimraf = require("rimraf");
const chalk = require('chalk');

const srcPath = './src/app/';

const srcFiles = fs.readdirSync(srcPath);
srcFiles.forEach(function (file, index) {
  const path = `${srcPath}${file}`;
  if (!isAModule(path)) {
    return;
  }
  const extractCommand = `./node_modules/.bin/ngx-translate-extract \
    --input ${srcPath}${file} \
    --format pot \
    --marker _ \
    --output ./i18n/${file}/extracted.pot`;
  const extractOutput = sh.exec(extractCommand, { silent: true }).stdout;
  if (extractOutput && extractOutput.includes('Extracted 0 strings')) {
    rimraf.sync(`./i18n/${file}`);
  } else {
    console.log(`${chalk.default.green('Extracted')} ${chalk.default.yellow(`${file}`)}`);
  }
});


/**
 * Checks whether a filename is ng-packagr module. A filename is a module when it is a directory that contains index.ts
 * file.
 * @parm {string} file Filename
 * @return {boolean} Whether a given filename is a module.
 */
function isAModule(file) {

  const stat = fs.statSync(file);
  if (stat.isDirectory()) {
    const dirContents = fs.readdirSync(file);
    return dirContents.includes('index.ts');
  }
  return false;
}
