#!env node

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

const util = require("util");
const fs = require("fs");
const path = require("path");
const webpack = require("webpack");

const fixturesFolder = path.join(__dirname, "fixtures");

const tests = fs
  .readdirSync(fixturesFolder)
  .map(name => {
    if (name[0] === ".") {
      return;
    }

    const inputTS = path.join(fixturesFolder, name, "input.ts");
    const inputJS = path.join(fixturesFolder, name, "input.js");

    return [name, fs.existsSync(inputTS) ? inputTS : inputJS];
  })
  .filter(Boolean);

(async function() {
  const targets = [
    await require("./builds/parcel")(tests, __dirname),
    await require("./builds/webpack3")(tests, __dirname),
    await require("./builds/webpack3-babel6")(tests, __dirname),
    await require("./builds/webpack3-babel7")(tests, __dirname),
    await require("./builds/webpack4")(tests, __dirname),
    await require("./builds/webpack4-babel6")(tests, __dirname),
    await require("./builds/webpack4-babel7")(tests, __dirname),
    await require("./builds/rollup")(tests, __dirname),
    await require("./builds/rollup-babel6")(tests, __dirname),
    await require("./builds/rollup-babel7")(tests, __dirname)
  ];

  await util.promisify(webpack)({
    context: __dirname,
    entry: "babel-polyfill",
    output: {
      filename: "polyfill-bundle.js"
    },
    plugins: [new webpack.optimize.OccurrenceOrderPlugin(true)]
  });

  const examplesDir = path.join(__dirname, "..");
  const html = path.join(examplesDir, "doc-sourcemapped.html");

  fs.writeFileSync(
    html,
    fs.readFileSync(html, "utf8").replace(
      /\n\s*<!-- INJECTED-START[\s\S]*INJECTED-END -->/,
      `
    <!-- INJECTED-START -->
    <!--
      Content generated by examples/sourcemapped/build.js.
      Run "yarn build" to update.
    -->${targets
      .map(({ target, fixtures }) => {
        return `\n    <h2>${target}</h2>${fixtures
          .map(
            ({ name, testFnName, scriptPath }) =>
              `\n    <script src="${path.relative(
                examplesDir,
                scriptPath
              )}"></script>` +
              `\n    <button onclick="${testFnName}()">Run ${name}</button>`
          )
          .join("")}`;
      })
      .join("")}
    <!-- INJECTED-END -->`
    )
  );

  console.log("DONE - If node is still running, just hit Ctrl+C. Parcel leaves things running for some reason.")
})();
