const path = require("path");

const { watch } = require("chokidar");

const nanoDevelopmentPlugin = () => {
  let restartTimeout;
  let watcher;
  let restartInProgress = false;
  let restartAgain = false;

  return {
    name: "vite-plugin-nano-development",
    configureServer(server) {
      const bigBinaryPackagesDir = path.resolve(
        process.cwd(),
        "node_modules",
        "@bigbinary"
      );

      server.httpServer?.on("close", () => {
        if (!watcher) return;

        watcher.close();
        watcher = null;
      });

      watcher = watch(bigBinaryPackagesDir, { ignoreInitial: true })
        .on("add", restartServer)
        .on("change", restartServer)
        .on("error", error =>
          // eslint-disable-next-line no-console
          console.error(`[nano-development-plugin] watcher error: ${error}`)
        );

      function restartServer(filePath) {
        if (!filePath.endsWith(".ready")) return;

        clearTimeout(restartTimeout);
        restartTimeout = setTimeout(() => {
          if (restartInProgress) {
            restartAgain = true;
          } else {
            doRestart();
          }
        }, 1000);
      }

      async function doRestart() {
        restartInProgress = true;
        try {
          await server.restart(true);
        } catch (error) {
          // eslint-disable-next-line no-console
          console.error(`[nano-development-plugin] restart error: ${error}`);
        } finally {
          setTimeout(() => {
            restartInProgress = false;

            if (restartAgain) {
              restartAgain = false;
              doRestart();
            }
          }, 1000);
        }
      }
    },
  };
};

module.exports = { nanoDevelopmentPlugin };
