const electron: typeof Electron = require('electron');

electron.contextBridge.exposeInMainWorld('electron', {
  ping: () => electron.ipcRenderer.invoke('ping'),
} satisfies Window['electron']);

/**
 * adapter for the ipcRenderer invoke function
 * - invokes an event to from the frontend to the backend
 *@param event
 * @returns the response from the backend
 */
function ipcInvoke<Event extends keyof EventPayloadMapping>(event: Event): Promise<EventPayloadMapping[Event]> {
  return electron.ipcRenderer.invoke(event);
}

/**
 * adapter for the ipcRenderer on function
 * - subscribes to an event from the backend
 * @param event
 */
function ipcOn<Event extends keyof EventPayloadMapping>(
  event: Event,
  subscribeFunction: SubscribeFunction<Event>,
): UnsubscribeFunction {
  const callback = (_: Electron.IpcRendererEvent, payload: EventPayloadMapping[Event]) => subscribeFunction(payload);
  electron.ipcRenderer.on(event, callback);
  return () => electron.ipcRenderer.off(event, callback);
}
