import { join } from "path";
import reader, { WorkBook, WorkSheet } from "xlsx";
import { readdirSync } from "fs";

let excelPath = join(__dirname, "..", "..", "Excel");
let excelFiles = readdirSync(excelPath);

const excelData = () => {
  return excelFiles.flatMap((fileName) => {
    const filePath = join(excelPath, fileName);
    if (!fileName.includes("raw_") && !fileName.includes("lock")) {
      const klinika_emer = fileName.split("_")[0];
      const wb: WorkBook = reader.readFile(filePath);
      const sheets: string[] = wb.SheetNames;
      return sheets.flatMap((sheet: string) => {
        const ws: WorkSheet = wb.Sheets[sheet];
        const data = reader.utils.sheet_to_json(ws);
        return data.map((record: any) => {
          record.klinika = klinika_emer;
          return record;
        });
      });
    } else {
      return;
    }
  });
};

export default excelData;
