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

const { LIST, VIEW } = EVENT_NAMES.RECORDS;
const METHODS = {
  LIST: 'List',
  VIEW: 'GetScratchData',
  VIEW_SCRATCH_DATA: 'GetScratchData',
};

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

  const handleRequest = async (event, methodName, attributes) => {
    const request = RecordDataManager.convertRequestData(attributes);
    const response = await grpcClientCall(client, methodName, request, event);
    return RecordDataManager.convertResponseData(response?.records || response?.record || response);
  };

  ipcMain.handle(LIST, (event, attributes) => handleRequest(event, METHODS.LIST, attributes));
  ipcMain.handle(VIEW, (event, id) => handleRequest(event, METHODS.VIEW, { id }));
}
