import path from "path";
import { GetAllEnvFiles } from "../watcher/watcher";
import DecodeAD1 from "./decode-ad1";
import DecodeAD2 from "./decode-ad2";
import DecodeEnv from "./decode-env";
import DecodeVeh from "./decode-veh";
import { ReplaceOwnerInfoWithClaimant } from "./decoder";

const folderScan = async (): Promise<FolderScanResult[]> => {
  //Get all ENV files for watched paths.
  const allEnvFiles = GetAllEnvFiles();
  //Run a simplified decode on them
  const returnedFiles: FolderScanResult[] = [];

  for (const filepath of allEnvFiles) {
    const parsedFilePath = path.parse(filepath);
    const extensionlessFilePath = path.join(
      parsedFilePath.dir,
      parsedFilePath.name,
    );

    const rawJob = {
      ...(await DecodeEnv(extensionlessFilePath)),
      ...(await DecodeAD1(extensionlessFilePath)),
      ...(await DecodeAD2(extensionlessFilePath)),
      ...(await DecodeVeh(extensionlessFilePath)),
    };
    const job = ReplaceOwnerInfoWithClaimant(rawJob);

    const scanResult: FolderScanResult = {
      id: job.ciecaid,
      filepath: filepath,
      cieca_id: job.ciecaid,
      clm_no: job.clm_no,
      owner: `${job.ownr_fn} ${job.ownr_ln} ${job.ownr_co_nm}`.trim(),
      vehicle:
        `${job.vehicle?.data.v_model_yr} ${job.vehicle?.data.v_make_desc} ${job.vehicle?.data.v_model_desc}`.trim(),
      ins_co_nm: job.ins_co_nm,
    };

    returnedFiles.push(scanResult);
  }
  //Build up the object and return it
  return returnedFiles;
};

export interface FolderScanResult {
  id?: string;
  filepath: string;
  cieca_id?: string;
  clm_no?: string;
  owner: string;
  ins_co_nm?: string;
  vehicle: string;
}

export default folderScan;
