import {Component} from 'react';

export default class extends Component {
  constructor(props) {
    super(props);

    if (!process.versions.hasOwnProperty('electron')) {
      this.ipcRenderer = ((window && window.require) ? window.require('electron').ipcRenderer : null);
    }
  }

  handlerList = {};
  ipcRenderer;

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

    this.handlerList = {};
  };

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

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

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

};