const { ipcMain, dialog } = require("electron");

const ipcTypes = require("../../src/ipc.types.commonjs");
const { mainWindow } = require("../main");
const _ = require("lodash");
const { store } = require("../electron-store");
const path = require("path");
var xlsx = require("node-xlsx");
const log = require("electron-log");

ipcMain.on(ipcTypes.default.audit.toMain.browseForFile, async (event, { sheetName }) => {
  const result = await dialog.showOpenDialog(mainWindow, {
    filters: [{ extensions: ["xls", "xlsx"], name: "Excel Files" }],
    properties: ["openFile"]
  });
  if (!result.canceled) {
    try {
      var obj = xlsx.parse(result.filePaths[0], { cellDates: true });
      store.set("auditFilePath", result.filePaths);
      event.sender.send(ipcTypes.default.audit.toRenderer.auditFilePath, {
        filePath: result.filePaths[0],
        sheets: obj.map((sheet) => sheet.name)
      });
    } catch (error) {
      console.log("Got some sort of err", error);
      log.error("Error when trying to read audit xlsx file", error);
      event.sender.send(ipcTypes.default.audit.toRenderer.auditError, error.meFssage);
    }
  }
});

ipcMain.on(ipcTypes.default.audit.toMain.runAudit, async (event, { sheetName }) => {
  try {
    const filePaths = store.get("auditFilePath");
    var obj = xlsx.parse(filePaths[0], { cellDates: true }); // parses a file

    const detailSheet = obj.find((sheet) => sheet.name === sheetName);
    const claimsArray = [];
    let foundHeaderRow, foundTotalRow;
    detailSheet.data.forEach((line) => {
      //Check the first element. If it's claim number, we have our header row. the next one is important.
      if (!foundHeaderRow && line[0] === "Claim Number") {
        foundHeaderRow = true;
      } else if (foundHeaderRow && !foundTotalRow && line[0] && line[0] !== "Grand Total") {
        //Add it to the array
        const row = {
          clm_no: line[0].startsWith("00") ? line[0].slice(2) : line[0],
          close_date: line[1],
          v_model_yr: line[3],
          v_makedesc: line[4],
          v_model: line[5],
          under20kmiles: line[6],
          pan_total: line[7],
          paa_total: line[8],
          pal_total: line[9],
          pam_total: line[10],
          eligible_db_price_total: Math.round((line[11] + Number.EPSILON) * 100) / 100,
          eligible_act_price_total: Math.round((line[12] + Number.EPSILON) * 100) / 100,
          expected_rps_dollars: Math.round((line[15] + Number.EPSILON) * 100) / 100,
          actual_rps_dollars: Math.round((line[16] + Number.EPSILON) * 100) / 100
        };
        claimsArray.push(row);
      } else {
        //   foundTotalRow = true;
      }
    });

    event.sender.send(ipcTypes.default.audit.toRenderer.auditClaimsArray, claimsArray);
  } catch (error) {
    console.log("ot some sort of err", error);
    log.error("Error when trying to read audit xlsx file", error);
    event.sender.send(ipcTypes.default.audit.toRenderer.auditError, error.message);
  }
});
