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

const { LIST, VIEW, CREATE, UPDATE, DELETE, RUN_JOB } = EVENT_NAMES.JOBS;
const METHODS = {
  LIST: 'List',
  VIEW: 'Get',
  CREATE: 'Create',
  UPDATE: 'Update',
  DELETE: 'Delete',
  RUN_JOB: 'RunJob',
};

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

  const handleRequest = async (event, methodName, attributes) => {
    const request = JobDataManager.convertRequestData(attributes);
    // let response;
    const response = await grpcClientCall(client, methodName, request, event);
    return JobDataManager.convertResponseData(response?.jobs || response?.job || response);
  };

  ipcMain.handle(LIST, (event, attributes) => handleRequest(event, METHODS.LIST, attributes));
  ipcMain.handle(VIEW, (event, id) => handleRequest(event, METHODS.VIEW, { id }));
  ipcMain.handle(CREATE, (event, attributes) => {
    console.log({ attributes });
    handleRequest(event, METHODS.CREATE, attributes);
  });
  ipcMain.handle(UPDATE, (event, attributes) => handleRequest(event, METHODS.UPDATE, attributes));
  ipcMain.handle(DELETE, (event, jobId) => handleRequest(event, METHODS.DELETE, { jobId }));
  ipcMain.handle(RUN_JOB, (event, jobId) => handleRequest(event, METHODS.RUN_JOB, { jobId }));
}
