import { ipcMain } from 'electron';
import IpcMainEvent = Electron.IpcMainEvent;

export function registerHandler(channel: IpcChannel, controller: IIpcController, handler: string): void {
  ipcMain.on(channel, (event: IpcMainEvent, payload: IIpcPayload) => {
    ((controller.get() as unknown) as { [x: string]: IpcHandler })
      [handler](payload.data)
      .then((result: unknown) => {
        const response: IIpcResponse = {
          id: payload.id,
          success: true,
          data: result,
        };
        event.reply(channel, response);
      })
      .catch((reason: Error) => {
        const response: IIpcResponse = {
          id: payload.id,
          success: false,
          error: reason.message,
        };
        event.reply(channel, response);
      });
  });
}
