import { ipcRenderer } from 'electron';
import { uuid } from '../../services/uuid';
import IpcRendererEvent = Electron.IpcRendererEvent;

const ipcClient: IIpcClient = {
  ask: (channel: IpcChannel, data?: unknown): Promise<unknown> => {
    const id = uuid();
    const payload: IIpcPayload = {
      id,
      data,
    };

    return new Promise((resolve: (value?: unknown) => void, reject: (reason?: Error) => void): void => {
      const listener = (event: IpcRendererEvent, response: IIpcResponse): void => {
        if (response.id === id) {
          if (response.success) {
            resolve(response.data);
          } else {
            reject(new Error(response.error));
          }
          ipcRenderer.removeListener(channel, listener);
        }
      };
      ipcRenderer.on(channel, listener);
      ipcRenderer.send(channel, payload);
    });
  },
};

export function nhentaiSaveFavorites(): Promise<void> {
  return ipcClient.ask(IpcChannel.NHENTAI_SAVE_FAVORITES) as Promise<void>;
}
