const fs = require('fs');
const path = require('path');
const { watch } = require('chokidar');
const { debounce } = require('lodash');
const minimist = require('minimist');
const templating = require('./templates');
const webpackConfig = require('./webpack.config');

/** @var {Object} argv */
const argv = minimist(process.argv);

function buildIndexHtml() {
  const html = templating.compile(!!argv.dev);

  fs.writeFileSync(path.resolve(webpackConfig.output.path, 'index.html'), html);
  console.log('compiled index.html');
}

const debouncedBuildIndexHtml = debounce(buildIndexHtml, 100, { leading: true, trailing: false });

function build() {
  if (argv.watch) {
    const templatesWatcher = watch('./templates/**/*');
    templatesWatcher.on('all', debouncedBuildIndexHtml);
  } else {
    buildIndexHtml();
  }
}

build();
