import { DBFFile } from "dbffile";
import log from "electron-log/main";
import _ from "lodash";
import deepLowerCaseKeys from "../../util/deepLowercaseKeys";
import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedPfh } from "./decode-pfh.interface";
import { platform } from "os";
import { findFileCaseInsensitive } from "./decoder-utils";

const DecodePfh = async (
  extensionlessFilePath: string,
): Promise<DecodedPfh> => {
  let dbf: DBFFile | null = null;
  if (platform.isWindows) {
    try {
      dbf = await DBFFile.open(`${extensionlessFilePath}.PFH`);
    } catch (error) {
      log.error("Error opening PFH File.", errorTypeCheck(error));
      dbf = await DBFFile.open(`${extensionlessFilePath}.PFH`);
      log.log("Trying to find PFH file using regular CIECA Id.");
    }

    if (!dbf) {
      log.error(`Could not find any PFH files at ${extensionlessFilePath}`);
      throw new Error(
        `Could not find any PFH files at ${extensionlessFilePath}`,
      );
    }
  } else {
    const possibleExtensions: string[] = [".pfh"];
    const filePath = await findFileCaseInsensitive(
      extensionlessFilePath,
      possibleExtensions,
    );
    try {
      if (!filePath) {
        log.error(`Could not find any PFH files at ${extensionlessFilePath}`);
        throw new Error(
          `Could not find any PFH files at ${extensionlessFilePath}`,
        );
      }
      dbf = await DBFFile.open(filePath);
    } catch (error) {
      log.error("Error opening PFH File.", errorTypeCheck(error));
      throw error;
    }
  }
  const rawDBFRecord = await dbf.readRecords(1);

  //AD2 will always have only 1 row.
  //Commented lines have been cross referenced with existing partner fields.

  const rawPfhData: DecodedPfh = deepLowerCaseKeys(
    _.pick(rawDBFRecord[0], [
      //TODO: Add typings for EMS File Formats.
      //TODO: Several of these fields will fail. Should extend schema to capture them.
      //"ID_PRO_NAM", //Remove
      "TAX_PRETHR",
      "TAX_THRAMT",
      "TAX_PSTTHR",
      //"TAX_TOW_IN", //Remove
      "TAX_TOW_RT",
      //"TAX_STR_IN", //Remove
      "TAX_STR_RT",
      //"TAX_SUB_IN", //Remove
      "TAX_SUB_RT",
      //"TAX_BTR_IN", //Remove
      "TAX_LBR_RT",
      "TAX_GST_RT",
      //"TAX_GST_IN", //Remove
      "ADJ_G_DISC",
      "ADJ_TOWDIS",
      "ADJ_STRDIS",
      //"ADJ_BTR_IN", //Remove
      "TAX_PREDIS",
    ]),
  );

  //Apply business logic transfomrations.

  //Standardize some of the numbers and divide by 100.

  rawPfhData.tax_prethr = (rawPfhData.tax_prethr ?? 0) / 100;
  rawPfhData.tax_pstthr = (rawPfhData.tax_pstthr ?? 0) / 100;
  rawPfhData.tax_tow_rt = (rawPfhData.tax_tow_rt ?? 0) / 100;
  rawPfhData.tax_str_rt = (rawPfhData.tax_str_rt ?? 0) / 100;
  rawPfhData.tax_sub_rt = (rawPfhData.tax_sub_rt ?? 0) / 100;
  rawPfhData.tax_lbr_rt = (rawPfhData.tax_lbr_rt ?? 0) / 100;
  rawPfhData.federal_tax_rate = (rawPfhData.tax_gst_rt ?? 0) / 100;
  delete rawPfhData.tax_gst_rt;

  return rawPfhData;
};
export default DecodePfh;
