const { ipcMain, app: electronApp, app, BrowserWindow } = require("electron");

const { default: ipcTypes } = require("../src/ipc.types.commonjs");
const { store } = require("./electron-store");
const log = require("electron-log");
const { ImportJobWithCloseDate } = require("./decoder/decoder");
const { ScrubEstimate } = require("./estimate-scrubber/estimate-scrubber");

//Import Ipc Handlers
require("./file-watcher/file-watcher-ipc");
require("./file-scan/file-scan-ipc");
require("./audit/audit-ipc");

console.log("*** Added IPC Handlers ***");

ipcMain.on("test", async (event, object) => {
  console.log("Received test IPC Command");
  event.reply("test-toRenderer", { status: 0, message: null });
});

ipcMain.on(ipcTypes.app.toMain.setAcceptableInsCoNm, (event, insCos) => {
  store.set("accepted_ins_co", insCos);
});

ipcMain.on(ipcTypes.store.get, (event, key) => {
  const val = store.get(key);
  event.sender.send(ipcTypes.store.response, { [key]: val });
});

ipcMain.on(ipcTypes.store.set, (event, key, val) => {
  store.set(key, val);

  const st = store.get();
  event.sender.send(ipcTypes.store.response, st);
});

ipcMain.on(ipcTypes.store.getAll, (event, obj) => {
  const val = store.get();
  event.sender.send(ipcTypes.store.response, val);
});

ipcMain.on(ipcTypes.app.toMain.getReleaseNotes, (event, obj) => {
  const showNotes = store.get("showChangeLog");
  if (showNotes) {
    const rn = require("./changelog.json")[electronApp.getVersion()];
    event.sender.send(ipcTypes.app.toRenderer.setReleaseNotes, rn);
  } else {
    event.sender.send(ipcTypes.app.toRenderer.setReleaseNotes, null);
  }
});

ipcMain.on(ipcTypes.app.toMain.importJob, (event, { filepath, close_date }) => {
  ImportJobWithCloseDate(filepath, close_date);
});

ipcMain.on(ipcTypes.app.toMain.log.debug, (event, ...obj) => {
  log.debug(obj);
});
ipcMain.on(ipcTypes.app.toMain.log.info, (event, ...obj) => {
  log.info(obj);
});
ipcMain.on(ipcTypes.app.toMain.log.warn, (event, ...obj) => {
  log.warn(obj);
});
ipcMain.on(ipcTypes.app.toMain.log.error, (event, ...obj) => {
  log.error(obj);
});

ipcMain.on(ipcTypes.app.toMain.getAppVersion, (event, obj) => {
  event.sender.send(ipcTypes.app.toRenderer.appVersion, app.getVersion());
});

ipcMain.handle(ipcTypes.app.toMain.scrubEstimate, (event, { job }) => {
  return ScrubEstimate({ job })
});

ipcMain.on(ipcTypes.app.toMain.openExternalWindow, (event, url) => {
  const externalWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  externalWindow.loadURL(url);

  // Optional: Open external links in default browser
  externalWindow.webContents.setWindowOpenHandler(({ url }) => {
    require('electron').shell.openExternal(url);
    return { action: 'deny' };
  });
});


ipcMain.on(ipcTypes.app.toMain.setInsRuleSet, (event, ins_rule_set) => {
  store.set("ins_rule_set", ins_rule_set);
});