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 { DecodedPfo, DecodedPfoLine } from "./decode-pfo.interface";
import { platform } from "@electron-toolkit/utils";
import { findFileCaseInsensitive } from "./decoder-utils";

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

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

  const rawDBFRecord = await dbf.readRecords(1);

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

  const rawPfoData: DecodedPfoLine = YNBoolConverter(
    deepLowerCaseKeys(
      _.pick(rawDBFRecord[0], [
        //TODO: Add typings for EMS File Formats.
        "TX_TOW_TY",
        "TOW_T_TY1",
        "TOW_T_IN1",
        "TOW_T_TY2",
        "TOW_T_IN2",
        "TOW_T_TY3",
        "TOW_T_IN3",
        "TOW_T_TY4",
        "TOW_T_IN4",
        "TOW_T_TY5",
        "TOW_T_IN5",
        "TOW_T_TY6",
        "TOW_T_IN6",
        "TX_STOR_TY",
        "STOR_T_TY1",
        "STOR_T_IN1",
        "STOR_T_TY2",
        "STOR_T_IN2",
        "STOR_T_TY3",
        "STOR_T_IN3",
        "STOR_T_TY4",
        "STOR_T_IN4",
        "STOR_T_TY5",
        "STOR_T_IN5",
        "STOR_T_TY6",
        "STOR_T_IN6",
      ]),
    ),
  );

  //Apply business logic transfomrations.

  return { cieca_pfo: rawPfoData };
};
export default DecodePfo;
