import { DBFFile } from "dbffile";
import log from "electron-log/main";
import _ from "lodash";
import deepLowerCaseKeys from "../../util/deepLowercaseKeys";
import errorTypeCheck from "../../util/errorTypeCheck";
import YNBoolConverter from "../../util/ynBoolConverter";
import {
  DecodedPfp,
  DecodedPfpLine,
  DecodedPfpLinesByType,
} from "./decode-pfp.interface";
import { platform } from "@electron-toolkit/utils";
import { findFileCaseInsensitive } from "./decoder-utils";

const DecodePfp = async (
  extensionlessFilePath: string,
): Promise<DecodedPfp> => {
  let dbf: DBFFile | null = null;
  if (platform.isWindows) {
    try {
      dbf = await DBFFile.open(`${extensionlessFilePath}.PFP`);
    } catch (error) {
      //PFP File only has 1 location.
      log.error("Error opening PFP File.", errorTypeCheck(error));
    }

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

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

  const rawPfpData: DecodedPfpLine[] = rawDBFRecord.map((record) => {
    const singleLineData: DecodedPfpLine = deepLowerCaseKeys(
      _.pick(record, [
        //TODO: Add typings for EMS File Formats.
        "PRT_TYPE",
        "PRT_TAX_IN",
        "PRT_TAX_RT",
        "PRT_MKUPP",
        "PRT_MKTYP",
        "PRT_DISCP",
        "PRT_TX_TY1",
        "PRT_TX_IN1",
        "PRT_TX_TY2",
        "PRT_TX_IN2",
        "PRT_TX_TY3",
        "PRT_TX_IN3",
        "PRT_TX_TY4",
        "PRT_TX_IN4",
        "PRT_TX_TY5",
        "PRT_TX_IN5",
      ]),
    );

    singleLineData.prt_tax_rt = singleLineData.prt_tax_rt / 100;
    return YNBoolConverter(singleLineData);
  });

  //Apply business logic transfomrations.

  //Convert array of lines to a hash object.
  const parsedPfpFile: DecodedPfpLinesByType = rawPfpData.reduce(
    (acc: DecodedPfpLinesByType, line: DecodedPfpLine) => {
      acc[line.prt_type] = line;
      return acc;
    },
    {} as DecodedPfpLinesByType,
  );

  return { parts_tax_rates: parsedPfpFile };
};

export default DecodePfp;
