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

const DecodeEnv = async (
  extensionlessFilePath: string,
): Promise<DecodedEnv> => {
  let dbf: DBFFile | null = null;

  if (platform.isWindows) {
    try {
      dbf = await DBFFile.open(`${extensionlessFilePath}.ENV`);
    } catch (error) {
      log.error("Error opening ENV File.", errorTypeCheck(error));
    }

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

  //AD2 will always have only 1 row.

  //TODO: Determine if there's any value to capture the whole ENV file.

  const rawEnvData: DecodedEnv = deepLowerCaseKeys(
    _.pick(rawDBFRecord[0], [
      //TODO: Add typings for EMS File Formats.
      //TODO: Several of these fields will fail. Should extend schema to capture them.
      //"EST_SYSTEM",
      "ESTFILE_ID",
    ]),
  );
  rawEnvData.ciecaid = rawEnvData.estfile_id;
  delete rawEnvData.estfile_id;

  //Apply business logic transfomrations.

  return rawEnvData;
};
export default DecodeEnv;
