import { grpcClientCall } from '../../utilities/grpcHelper';
import { EVENT_NAMES } from '../../constants/define';
import { ScrapingDataManager } from '../../mapping';
const grpc = require('@grpc/grpc-js');
const { ipcMain } = require('electron');

const { VIEW, UPDATE } = EVENT_NAMES.SCRAPING_DATA;
const METHODS = {
  VIEW_SCRATCH_DATA: 'GetScratchData',
  UPDATE_SCRATCH_DATA: 'UpdateScratchData',
};

export default function ScrapingDataClient(mainProto, SERVER_URL, options) {
  const client = new mainProto.DataJobController(SERVER_URL, grpc.credentials.createInsecure(), options);

  const handleRequest = async (event, methodName, attributes) => {
    const request = ScrapingDataManager.convertRequestData(attributes);
    const response = await grpcClientCall(client, methodName, request, event);
    return ScrapingDataManager.convertResponseData(response);
  };

  ipcMain.handle(VIEW, (event, attributes) => handleRequest(event, METHODS.VIEW_SCRATCH_DATA, attributes));
  ipcMain.handle(UPDATE, (event, attributes) => handleRequest(event, METHODS.UPDATE_SCRATCH_DATA, attributes));
}
