import reader from "xlsx";
import { getJsDateFromExcel } from "excel-date-to-js";

import { readdirSync, writeFileSync } from "fs";
import { join } from "path";

const excelPath = join(__dirname, "..", "..", "Excel");

const excelFiles = readdirSync(excelPath);

const readExcel = (filePath: string) => {
  let data: unknown[] = [];
  const file = reader.readFile(filePath);
  const sheets = file.SheetNames;
  for (let i = 0; i < sheets.length; i++) {
    const temp = reader.utils.sheet_to_json(file.Sheets[file.SheetNames[i]]);
    temp.forEach((res) => {
      data.push(res);
    });
  }
  return data;
};

const recordsToJson = () => {
  let i = 0;
  let records: any[] = [];
  excelFiles.every((file) => {
    if (!file.includes("raw_") && !file.includes("lock")) {
      const excelFile = join(excelPath, file);
      const data = readExcel(excelFile);
      const klinika_emer = file.split("_")[0];
      const klinika: any = {
        emer: klinika_emer,
        shtrimi: [],
      };
      data.every((record: any) => {
        i++;
        if (record.EMER !== "" && record.MBIEMER !== "") {
          let datelindja = null;
          let data_shtrimit = null;
          try {
            datelindja = getJsDateFromExcel(record.DATELINDJA_KORIGJ);
            data_shtrimit = getJsDateFromExcel(record.DT_SHTRIMI_KORIGJ);
          } catch (error) {
            console.log(i, record.EMER, record.MBIEMER);
            // return false;
          }
          const trajtimi = {
            trajtimi:
              record["TRAJTIMI SPITALOR Urgjence"] ||
              record["TRAJTIMI SPITALOR Pavion"],
          };
          const diagnoza = {
            emer: record.DIAGNOZA,
            kodi_dg_icd_9: record["Kodi DG  ICD-9"],
          };
          const pacienti = {
            emer: record.EMER,
            mbiemer: record.MBIEMER,
            mosha: record.MOSHA,
            datelindja,
            gjinia: record.GJINIA,
            error: record.ERROR,
          };
          const shtrimi = {
            nr: i,
            data_shtrimit,
            dite_qendrimi: record["DITE QENDRIMI NE SPITAL"],
            pacienti,
            diagnoza,
            trajtimi,
          };
          klinika.shtrimi.push(shtrimi);
        }
        return true;
      });
      records.push(klinika);
      console.log(`Mbaroi ${klinika_emer}`);
    }
    return true;
  });
  const jsonFile = join(__dirname, "..", "..", "JSON", "records.json");
  writeFileSync(jsonFile, JSON.stringify(records));
};

export default recordsToJson;
