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

const { LIST, VIEW, CREATE, UPDATE } = EVENT_NAMES.USERS;
const METHODS = {
  LIST: 'List',
  VIEW: 'Retrieve',
  CREATE: 'Create',
  UPDATE: 'Update',
};

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

  const handleRequest = async (event, methodName, attributes) => {
    const request = UserDataManager.convertRequestData(attributes);
    const response = await grpcClientCall(client, methodName, request, event);
    return UserDataManager.convertResponseData(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) => handleRequest(event, METHODS.CREATE, attributes));
  ipcMain.handle(UPDATE, (event, attributes) => handleRequest(event, METHODS.UPDATE, attributes));
}
