const { ipcMain, dialog, BrowserWindow } = require("electron");
const { StartWatcher, StopWatcher } = require("./file-watcher");
const ipcTypes = require("../../src/ipc.types.commonjs");
const _ = require("lodash");
const { store } = require("../electron-store");
const path = require("path");

ipcMain.on(
  ipcTypes.default.fileWatcher.toMain.filepathsGet,
  async (event, object) => {
    event.reply(
      ipcTypes.default.fileWatcher.toRenderer.filepathsList,
      store.get("filePaths")
    );
  }
);

ipcMain.on(ipcTypes.default.fileWatcher.toMain.start, async (event, arg) => {
  if ((arg && arg.startup && store.get("runWatcherOnStartup")) || !arg) {
    StartWatcher();
  }

  // event.sender.send(ipcTypes.default.fileWatcher.toRenderer.startSuccess);
  event.sender.send(
    ipcTypes.default.fileWatcher.toRenderer.filepathsList,
    store.get("filePaths")
  );
  // event.sender.send(ipcTypes.default.fileWatcher.toRenderer.startSuccess);
});

ipcMain.on(ipcTypes.default.fileWatcher.toMain.stop, async (event, arg) => {
  StopWatcher();
});

ipcMain.on(ipcTypes.default.fileWatcher.toMain.addPath, async (event, arg) => {
  const parentWindow = BrowserWindow.fromWebContents(event.sender);
  const result = await dialog.showOpenDialog(parentWindow, {
    properties: ["openDirectory"],
  });

  StopWatcher();
  store.set("filePaths", _.union(result.filePaths, store.get("filePaths")));
  const newFilePaths = store.get("filePaths");

  event.sender.send(
    ipcTypes.default.fileWatcher.toRenderer.filepathsList,
    newFilePaths
  );
});

ipcMain.on(
  ipcTypes.default.fileWatcher.toMain.removePath,
  async (event, arg) => {
    StopWatcher();

    store.set(
      "filePaths",
      store.get("filePaths").filter((k) => {
        const kf = path.parse(k);
        const argf = path.parse(arg);
        return kf.dir + kf.base !== argf.dir + argf.base;
      })
    );

    const newFilePaths = store.get("filePaths");
    //console.log("newFilePaths", newFilePaths);

    event.sender.send(
      ipcTypes.default.fileWatcher.toRenderer.filepathsList,
      newFilePaths
    );
  }
);
