const chokidar = require("chokidar");
const ipcTypes = require("../../src/ipc.types.commonjs");
const path = require("path");
const { ImportJob } = require("../decoder/decoder");
const { BrowserWindow } = require("electron");
const { store } = require("../electron-store");
const {
  NewNotification,
} = require("../notification-wrapper/notification-wrapper");
const log = require("electron-log");
//const Nucleus = require("nucleus-nodejs");
var watcher;

async function StartWatcher() {
  const filePaths = store.get("filePaths") || [];
  log.info("Use polling? ", store.get("polling").enabled);
  if (filePaths.length === 0) {
    NewNotification({
      title: "RPS Watcher cannot start",
      body: "Please set the appropriate file paths and try again.",
    });
    log.warn("Cannot start watcher. No file paths set.");
    return [];
  }

  if (watcher) {
    try {
      log.info("Trying to close watcher - it already existed.");
      await watcher.close();

      log.info("Watcher closed successfully!");
    } catch (error) {
      log.error("Error trying to close Watcher.", error);
    }
  }

  watcher = chokidar.watch(filePaths, {
    ignored: (fp, stats) => {
      const p = path.parse(fp);
      return p.ext !== "" && p.ext.toUpperCase() !== ".ENV";
    },
    usePolling: store.get("polling").enabled || false,
    interval: store.get("polling").pollingInterval || 1000,
    persistent: true,
    ignoreInitial: true,
    awaitWriteFinish: {
      pollInterval: 500,
      stabilityThreshold: 2000,
    },
  });

  watcher
    .on("add", async function (path) {
      console.log("File", path, "has been added");
      HandleNewFile(path);
    })
    // .on("addDir", function (path) {
    //   console.log("Directory", path, "has been added");
    // })
    .on("change", async function (path) {
      console.log("File", path, "has been changed");
      HandleNewFile(path);
    })
    // .on("unlink", function (path) {
    //   console.log("File", path, "has been removed");
    // })
    // .on("unlinkDir", function (path) {
    //   console.log("Directory", path, "has been removed");
    // })
    .on("error", function (error) {
      log.error("Error in Watcher", error);
      const b = BrowserWindow.getFocusedWindow();
      if (b) {
        b.webContents.send(
          ipcTypes.default.fileWatcher.toRenderer.error,
          error
        );
      }
      // Nucleus.track("WATCHER_ERROR", error);
    })
    .on("ready", onWatcherReady)
    .on("raw", function (event, path, details) {
      // This event should be triggered everytime something happens.
      // console.log("Raw event info:", event, path, details);
    });

  return filePaths;
}

function onWatcherReady() {
  log.info("Watcher ready!");
  const b = BrowserWindow.getAllWindows()[0];
  b.webContents.send(ipcTypes.default.fileWatcher.toRenderer.startSuccess);
  NewNotification({
    title: "RPS Watcher Started",
    body: "Newly exported estimates will be automatically uploaded.",
  });
  log.info("Confirmed watched paths:", watcher.getWatched());
}

async function StopWatcher() {
  if (watcher) {
    await watcher.close();
    log.info("Watcher stopped.");
    const b = BrowserWindow.getAllWindows()[0];
    b.webContents.send(ipcTypes.default.fileWatcher.toRenderer.stopSuccess);
    NewNotification({
      title: "RPS Watcher Stopped",
      body: "Estimates will not be automatically uploaded.",
    });
  }
}

exports.StartWatcher = StartWatcher;
exports.StopWatcher = StopWatcher;
exports.watcher = watcher;

async function HandleNewFile(path) {
  //  Nucleus.track("IMPORT_JOB_FROM_WATCHER");
  await ImportJob(path);
}
