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

const ipcTypes = require("../../src/ipc.types.commonjs");
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 parentWindow = BrowserWindow.fromWebContents(event.sender);
  const result = await dialog.showOpenDialog(parentWindow, {
    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;

    let clmIndex,
      close_dateIndex,
      v_model_yrIndex,
      v_makedescIndex,
      v_modelIndex,
      under20kmilesIndex,
      pan_totalIndex,
      paa_totalIndex,
      pal_totalIndex,
      pam_totalIndex,
      eligible_db_price_totalIndex,
      eligible_act_price_totalIndex,
      expected_rps_dollarsIndex,
      actual_rps_dollarsIndex;

    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;
        //Set all of the indexes to match the titles.

        clmIndex = line.findIndex((l) => l === "Claim Number");
        close_dateIndex = line.findIndex((l) => l === "Ready for Pay Date");
        v_model_yrIndex = line.findIndex((l) => l === "Vehicle Year");
        v_makedescIndex = line.findIndex((l) => l === "Vehicle Make");
        v_modelIndex = line.findIndex((l) => l === "Vehicle Model");
        under20kmilesIndex = line.findIndex((l) => l === "Under 20K");
        pan_totalIndex = line.findIndex((l) => l === "OE Part Prices");
        paa_totalIndex = line.findIndex((l) => l === "AM Part Prices");
        pal_totalIndex = line.findIndex((l) => l === "Recycled Part Prices");
        pam_totalIndex = line.findIndex((l) => l === "Reman & Other Part Prices");
        eligible_db_price_totalIndex = line.findIndex((l) => l === "(a) Eligible OEM Part Prices");
        eligible_act_price_totalIndex = line.findIndex((l) => l === "(b) Eligible Actual Part Prices");
        expected_rps_dollarsIndex = line.findIndex((l) => l === "(e) Expected RPS $ ");
        actual_rps_dollarsIndex = line.findIndex((l) => l === "(f) Actual RPS $");
      } else if (foundHeaderRow && !foundTotalRow && line[0] && line[0] !== "Grand Total") {
        //Add it to the array

        const row = {
          clm_no: line[clmIndex].startsWith("00") ? line[clmIndex].slice(2) : line[clmIndex],
          close_date: line[close_dateIndex],
          v_model_yr: line[v_model_yrIndex],
          v_makedesc: line[v_makedescIndex],
          v_model: line[v_modelIndex],
          under20kmiles: line[under20kmilesIndex],
          pan_total: line[pan_totalIndex],
          paa_total: line[paa_totalIndex],
          pal_total: line[pal_totalIndex],
          pam_total: line[pam_totalIndex],
          eligible_db_price_total: Math.round((line[eligible_db_price_totalIndex] + Number.EPSILON) * 100) / 100,
          eligible_act_price_total: Math.round((line[eligible_act_price_totalIndex] + Number.EPSILON) * 100) / 100,
          expected_rps_dollars: Math.round((line[expected_rps_dollarsIndex] + Number.EPSILON) * 100) / 100,
          actual_rps_dollars: Math.round((line[actual_rps_dollarsIndex] + 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);
  }
});
