const minimist = require("minimist");
const { parseArgs } = require("./parseArgs");
const chokidar = require("chokidar");
const { coreLogic } = require("./coreLogic");

async function main() {
  try {
    const args = minimist(process.argv.slice(2));

    const {
      suluDir,
      buildOutputPath,
      manifests,
      version,
      options: { reloadOnChanges, incrementalBuild },
      log,
    } = parseArgs({
      writeFolder: args.writeFolder,
      suluDir: args.suluDir,
      writeDir: args.writeDir,
      pluginPaths: args.pluginPaths,
      version: args.version,
      _w: args.w,
      _v: args.v,
      _o: args.o,
      _s: args.s,
      _p: args.p,
      _t: args.t,
    });

    coreLogic({
      incrementalBuild,
      buildOutputPath,
      version,
      log,
      suluDir,
      manifests,
    });

    if (reloadOnChanges) {
      const watcher = chokidar.watch(
        [suluDir, ...manifests.map((m) => m.absolutePath)],
        {
          persistent: true,
          ignored: (path) => {
            const r = [
              "node_modules",
              ".git",
              "yarn.lock",
              "yarn-error.log",
            ].find((x) => path.includes(x));
            return !!r;
          },
        }
      );
      let isReady = false;
      watcher.on("ready", () => {
        isReady = true;
      });
      watcher.on("change", (eventType) => {
        console.log(`>>>>> Changes detected, reloading: ${eventType} <<<<<`);
        coreLogic({
          incrementalBuild,
          buildOutputPath,
          version,
          log,
          suluDir,
          manifests,
        });
      });
      watcher.on("add", (eventType) => {
        if (isReady) {
          console.log(
            `>>>>> Changes detected (file added), reloading: ${eventType} <<<<<`
          );
          coreLogic({
            incrementalBuild,
            buildOutputPath,
            version,
            log,
            suluDir,
            manifests,
          });
        }
      });
      watcher.on("unlink", (eventType) => {
        console.log(
          `>>>>> Changes detected (file removed), reloading: ${eventType}`
        );
        coreLogic({
          incrementalBuild,
          buildOutputPath,
          version,
          log,
          suluDir,
          manifests,
        });
      });
    }
  } catch (e) {
    console.log("Error occured", e);
    process.exit(99);
  }
}

main();
