import {Component} from 'react';
import {getIPCRenderer} from '../../utils';

const ipcRenderer = getIPCRenderer();

export default class extends Component {
  handlerList = {};

  componentWillUnmount() {
    if (ipcRenderer) {
      for (let name in this.handlerList) {
        if (this.handlerList.hasOwnProperty(name)) {
          ipcRenderer.removeListener(name, this.handlerList[name]);
        }
      }
    }

    this.handlerList = {};
  };

  sendRequest = (name, data) => {
    if (ipcRenderer) {
      ipcRenderer.send(name, data);
    }
  };

  sendSyncRequest = (name, data) => {
    if (ipcRenderer) {
      return ipcRenderer.sendSync(name + '_sync', data);
    } else {
      return {
        Success: false,
        Error: 'IPC not available. Running in browser?',
      };
    }
  };

  setRequestHandler = (name, callback) => {
    if (ipcRenderer) {
      this.handlerList[name] = callback;
      ipcRenderer.on(name, callback);
    }
  };

};