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

@injectable()
export abstract class IpcServer {
  protected answer(channel: IpcChannels, handler: (data?: any) => Promise<any>): void {
    ipcMain.on(channel, (event: IpcMainEvent, payload: IIpcPayload) => {
      handler(payload.data)
        .then((result: any) => {
          const response: IIpcResponse = {
            id: payload.id,
            success: true,
            data: result,
          };
          event.reply(channel, response);
        })
        .catch((reason: any) => {
          const response: IIpcResponse = {
            id: payload.id,
            success: false,
            error: reason.toString(),
          };
          event.reply(channel, response);
        });
    });
  }

  protected send(window: BrowserWindow, channel: IpcChannels, data: any): void {
    window.webContents.send(channel, data);
  }
}
