import { DBFFile } from "dbffile";
import log from "electron-log/main";
import _ from "lodash";
import deepLowerCaseKeys from "../../util/deepLowercaseKeys";
import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedTtl, DecodedTtlLine } from "./decode-ttl.interface";
import { platform } from "@electron-toolkit/utils";
import { findFileCaseInsensitive } from "./decoder-utils";

const DecodeTtl = async (
  extensionlessFilePath: string,
): Promise<DecodedTtl> => {
  let dbf: DBFFile | null = null;
  if (platform.isWindows) {
    try {
      dbf = await DBFFile.open(`${extensionlessFilePath}.TTL`);
    } catch (error) {
      log.error("Error opening TTL File.", errorTypeCheck(error));
    }

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

  const rawDBFRecord = await dbf.readRecords(1);

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

  const rawTtlData: DecodedTtlLine = deepLowerCaseKeys(
    _.pick(rawDBFRecord[0], [
      //TODO: Add typings for EMS File Formats.
      "G_TTL_AMT",
      "G_BETT_AMT",
      "G_RPD_AMT",
      "G_DED_AMT",
      "G_CUST_AMT",
      "G_AA_AMT",
      "N_TTL_AMT",
      "PREV_NET",
      "SUPP_AMT",
      "N_SUPP_AMT", //Previously commented. Possible issue.
      "G_UPD_AMT",
      "G_TTL_DISC",
      "G_TAX",
      "GST_AMT",
    ]),
  );

  //Apply business logic transfomrations.

  return {
    clm_total: rawTtlData.g_ttl_amt || 0,
    depreciation_taxes: rawTtlData.g_bett_amt || 0, //TODO: Find where this needs to  be filled from
    cieca_ttl: { data: rawTtlData },
  };
};
export default DecodeTtl;
