import Electrobun, { Electroview } from "electrobun/view";

const listeners = new Map();

const rpc = Electroview.defineRPC({
  maxRequestTime: 30000,
  handlers: {
    requests: {},
    messages: {
      "*": (channel, data) => {
        const channelListeners = listeners.get(channel);
        if (!channelListeners) {
          return;
        }

        for (const callback of channelListeners) {
          callback(data);
        }
      },
    },
  },
});

const electroview = new Electrobun.Electroview({ rpc });

function onIPCData(channel, callback) {
  if (!listeners.has(channel)) {
    listeners.set(channel, new Set());
  }
  listeners.get(channel).add(callback);
}

function removeAllListeners(channel) {
  listeners.delete(channel);
}

function sendIPC(channel, data) {
  if (channel === "getData") {
    electroview.rpc.request.getData({});
    return;
  }

  if (channel === "authenticateOTP") {
    electroview.rpc.request.authenticateOTP({ otp: data });
    return;
  }

  if (channel === "window-minimize") {
    electroview.rpc.request.minimizeWindow({});
    return;
  }

  if (channel === "window-maximize") {
    electroview.rpc.request.maximizeWindow({});
    return;
  }

  if (channel === "window-close") {
    electroview.rpc.request.closeWindow({});
    return;
  }

  console.warn(`Unhandled IPC channel: ${channel}`);
}

window.electronAPI = {
  onIPCData,
  sendIPC,
  minimize: () => sendIPC("window-minimize"),
  maximize: () => sendIPC("window-maximize"),
  close: () => sendIPC("window-close"),
  removeAllListeners,
};

export default window.electronAPI;
