//Set up all the IPC handlers.
import {
  setWatcherPolling,
  updateAvailable,
  updateChecking,
  updateDownloaded,
  updateProgress,
  watcherError,
  watcherStarted,
  watcherStopped,
} from "@renderer/redux/app.slice";
import store from "@renderer/redux/redux-store";
import ipcTypes from "../../../util/ipcTypes.json";
import { auth } from "./firebase";
import { notification } from "antd";
import i18n from "./i18n";

const ipcRenderer = window.electron.ipcRenderer;
const dispatch = store.dispatch;

ipcRenderer.on(
  ipcTypes.toRenderer.test,
  (_event: Electron.IpcRendererEvent, arg) => {
    console.log("Received test message from main process");
    console.log(arg);
  },
);

ipcRenderer.on(ipcTypes.toRenderer.user.getToken, async () => {
  const token = await auth.currentUser?.getIdToken();
  ipcRenderer.send(ipcTypes.toMain.user.getTokenResponse, token);
});

ipcRenderer.on(ipcTypes.toRenderer.watcher.started, () => {
  console.log("Watcher has started");
  dispatch(watcherStarted());
});

ipcRenderer.on(ipcTypes.toRenderer.watcher.stopped, () => {
  console.log("Watcher has stopped");
  dispatch(watcherStopped());
});

ipcRenderer.on(
  ipcTypes.toRenderer.watcher.error,
  (_event: Electron.IpcRendererEvent, error: string) => {
    console.log("Watcher has encountered an error");
    console.log(error);
    dispatch(watcherError(error));
  },
);

//Update Handlers
ipcRenderer.on(ipcTypes.toRenderer.updates.checking, () => {
  console.log("Checking for updates...");
  dispatch(updateChecking());
});

ipcRenderer.on(ipcTypes.toRenderer.updates.available, () => {
  dispatch(updateAvailable());
});

ipcRenderer.on(
  ipcTypes.toRenderer.updates.downloading,
  (_event: Electron.IpcRendererEvent, arg) => {
    console.log("*** ARg", arg);
    dispatch(
      updateProgress({
        progress: Math.round(arg.percent),
        speed: arg.bytesPerSecond,
      }),
    );
  },
);

ipcRenderer.on(ipcTypes.toRenderer.updates.downloaded, () => {
  dispatch(updateDownloaded());
});

ipcRenderer.on(
  ipcTypes.toRenderer.watcher.polling,
  (_event: Electron.IpcRendererEvent, arg) => {
    dispatch(
      setWatcherPolling({ enabled: arg.enabled, interval: arg.interval }),
    );
  },
);

ipcRenderer.on(
  ipcTypes.toRenderer.general.showErrorMessage,
  (_event: Electron.IpcRendererEvent, error) => {
    notification.error({
      message: i18n.t("errors.notificationtitle"),
      description: error,
    });
  },
);
