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

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

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

export function login(credentials: ICredentials): Promise<void> {
  return ipcClient.ask(IpcChannels.LOGIN, credentials);
}

export function isLoggedIn(): Promise<boolean> {
  return ipcClient.ask(IpcChannels.LOGGED_IN);
}
