const path = require('path');
const fs = require('fs');

const DIR_BUILT_SCRIPTS = path.join('build', 'scripts');
const DIR_OUT = path.join('build', 'assets', 'scripts');
const FILE_MAIN = 'main.js';

let doneFiles = [];
let full = `
var exports = {};

function __extends(d,b) {
  d.prototype = b.prototype;
}
`;

const CRUMMY_EXTENDS = /var __extends =([\S\s]*?)\}\)\(\)\;/gm;
const ES5_DEFINED = /Object\.defineProperty\(exports, \"__esModule\", \{ value\: true \}\)\;/gm

const outputFix = (output, dir) => {
  let out = output
    .replace(CRUMMY_EXTENDS, '')
    .replace(/exports\.\_\_esModule\ =\ true\;/gm, '')
  ;
  
  // Replace requires with exports.
  const reg = /var\ (.*?)\ \= require\("(.*?)"\)\;/gm;
  const matches = out.matchAll(reg);
  let match;
  while(!(match = matches.next()).done) {
    const exp = new RegExp(`${match.value[1]}\.`, 'gm');
    const filePath = path.join(dir, match.value[2]);
    scanFile(filePath, path.dirname(filePath));
    out = out.replace(match.value[0], '').replace(exp, 'exports.');
  }

  out = out
    .replace(CRUMMY_EXTENDS, '')
    .replace(ES5_DEFINED, '')
    .replace(/exports\.(.*?) \= void 0\;/gm, '')
    .replace(/\ \ \ \ /gm, '  ')
  ;

  return out;
}

const scanFile = (file, dir) => {
  if(!file.endsWith('.js')) file += '.js';
  if(doneFiles.indexOf(file) !== -1) return;
  doneFiles.push(file);
  const contents = fs.readFileSync(file, 'utf-8');
  const f = outputFix(contents, dir);
  full = full + `\n//${file}\n` + f;
}

const scanDir = dir => fs.readdirSync(dir).forEach(file => {
  if(!file.endsWith('.js')) return;
  const joint = path.join(DIR_BUILT_SCRIPTS, file);
  const stat = fs.statSync(joint);
  if(stat.isDirectory()) {
    scanDir(joint);
  } else {
    scanFile(joint, dir);
  }
});

scanFile(path.join(DIR_BUILT_SCRIPTS, FILE_MAIN), DIR_BUILT_SCRIPTS);

if(!fs.existsSync(DIR_OUT)) fs.mkdirSync(DIR_OUT);
fs.writeFileSync(path.join(DIR_OUT, FILE_MAIN), full);