import { ipcMain } from 'electron';
import IpcMainEvent = Electron.IpcMainEvent;
import { mainWindow } from '../../main';
import { isLoggedIn, login } from '../services/nhentai-crawler';

export const ipcServer: IIpcServer = {
  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);
        });
    });
  },
  send: (channel: IpcChannels, data: any): void => {
    mainWindow.webContents.send(channel, data);
  },
};

ipcServer.answer(IpcChannels.LOGIN, (credentials: ICredentials) => {
  return login(credentials.name, credentials.password);
});

ipcServer.answer(IpcChannels.LOGGED_IN, () => {
  return isLoggedIn();
});
