import { DBFFile } from "dbffile";
import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedStlLine } from "../decoder/decode-stl.interface";
import { stlFieldLineDescriptors } from "../util/ems-interface/fielddescriptors/stl-field-descriptors";
import {
  deleteEmsFileIfExists,
  generateEmsOutFilePath,
} from "../util/ems-util";
import uppercaseObjectKeys from "../util/uppercaseObjectKeys";
import { EmsPartsOrder } from "./ems-parts-order-interfaces";

const EmsPartsOrderGenerateStlFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    //TODO: Add CIECA STL to parts order.
    const records = Object.keys(partsOrder.job.cieca_stl?.data).map((key) => {
      const record: DecodedStlLine = partsOrder.job.cieca_stl.data[key];
      return uppercaseObjectKeys(record);
    });

    await deleteEmsFileIfExists(
      generateEmsOutFilePath(`${partsOrder.job.ciecaid}.STL`),
    );

    const dbf: DBFFile = await DBFFile.create(
      generateEmsOutFilePath(`${partsOrder.job.ciecaid}.STL`),
      stlFieldLineDescriptors,
    );

    await dbf.appendRecords(records);
    console.log(`${records.length} STL file records added.`);
    return true;
  } catch (error) {
    console.error("Error generating STL file:", errorTypeCheck(error));
    return false;
  }
};

export default EmsPartsOrderGenerateStlFile;
