var Terser = require('terser');
var fs = require('fs');
var path = require('path');

function getAllFiles(dirPath, arrayOfFiles, extension) {
  let files = fs.readdirSync(dirPath);

  arrayOfFiles = arrayOfFiles || [];
  extension = extension || 'js';

  files.forEach(function (file) {
    if (fs.statSync(dirPath + '/' + file).isDirectory()) {
      arrayOfFiles = getAllFiles(dirPath + '/' + file, arrayOfFiles);
    } else {
      arrayOfFiles.push(path.join(__dirname, dirPath, '/', file));
    }
  });

  return arrayOfFiles.filter((path) =>
    path.match(new RegExp(`.${extension}$`))
  );
}

async function minifyFiles(filePaths) {
  await Promise.all(
    filePaths.map(async (filePath) => {
      try {
        fs.writeFileSync(
          filePath,
          (
            await Terser.minify(fs.readFileSync(filePath, 'utf8'), {
              compress: true,
              mangle: true,
            })
          ).code
        );
      } catch (e) {
        console.log('Error parsing filePath: ', filePath);
        throw e;
      }
    })
  );
}

const jsFiles = getAllFiles('./dist');
minifyFiles(jsFiles).then((r) => r);

const indexHtml = './dist/index.html';
fs.readFile(indexHtml, 'utf-8', function (err, data) {
  if (err) throw err;

  let result = data.replace('src="/src/main.tsx"', 'src="/src/main.js"');

  fs.writeFile(indexHtml, result, 'utf-8', function (err) {
    if (err) throw err;
  });
});
