import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

export type Channels =
  | 'ipc-example'
  | 'download-progress'
  | 'launch-minecraft'
  | 'installation-status'
  | 'get-server-status'
  | 'close-app'
  | 'minimize-app'
  | 'save-pack-config'
  | 'load-pack-config'
  | 'update-available'
  | 'install-update'
  | 'get-installed-versions'
  | 'get-available-versions'
  | 'minecraft-log'
  | 'minecraft-error'
  | 'overall-progress'
  | 'stop-minecraft'
  | 'minecraft-started'
  | 'minecraft-stopped';

const electronHandler = {
  ipcRenderer: {
    sendMessage(channel: Channels, ...args: unknown[]) {
      ipcRenderer.send(channel, ...args);
    },
    on(channel: Channels, func: (...args: unknown[]) => void) {
      const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
        func(...args);
      ipcRenderer.on(channel, subscription);

      return () => {
        ipcRenderer.removeListener(channel, subscription);
      };
    },
    once(channel: Channels, func: (...args: unknown[]) => void) {
      ipcRenderer.once(channel, (_event, ...args) => func(...args));
    },
    invoke(channel: Channels, ...args: unknown[]): Promise<any> {
      return ipcRenderer.invoke(channel, ...args);
    },
  },
};

contextBridge.exposeInMainWorld('electron', electronHandler);

export type ElectronHandler = typeof electronHandler;
