const path = require("path");
const fs = require("fs");
const { store } = require("../electron-store");
const log = require("electron-log");
const fsPromises = fs.promises;
const { DecodeEstimate } = require("../decoder/decoder");
//const Nucleus = require("nucleus-nodejs");

async function GetListOfEstimates() {
 // Nucleus.track("SCAN_ALL_ESTIMATES");
  log.info("Scanning all local estimates..");
  const ListOfEnvFiles = await GetEnvFiles();
  const ListOfSummarizedEstimates = await ReadAllEstimates(ListOfEnvFiles);
  const FilteredListOfSummarizedEstimates = ListOfSummarizedEstimates.filter(
    (j) => !j.ERROR
  );

  log.log(
    "Number of estimates filtered on file scan due to error: ",
    ListOfSummarizedEstimates.length - FilteredListOfSummarizedEstimates.length
  );
  return FilteredListOfSummarizedEstimates;
}

async function ReadAllEstimates(ListOfEnvFiles) {
  return await Promise.all(
    ListOfEnvFiles.map(async (e) => await DecodeEstimate(e, true))
  );
}

async function GetEnvFiles() {
  const filePaths = store.get("filePaths");
  const allFilePaths = [];
  await Promise.all(
    filePaths.map(async (fp) => {
      const envFilesInDir = (await fsPromises.readdir(fp)).filter((p) =>
        p.toUpperCase().includes(".ENV")
      );

      envFilesInDir.map((envFileName) => {
        allFilePaths.push(path.join(fp, envFileName));
        return null;
      });
    })
  );
  return allFilePaths;
}

async function DeleteAllEms() {
  try {
    const filePaths = store.get("filePaths");
    const allFilePaths = [];
    await Promise.all(
      filePaths.map(async (fp) => {
        const allFilesinDir = await fsPromises.readdir(fp);

        allFilesinDir.map((envFileName) => {
          allFilePaths.push(path.join(fp, envFileName));
          return null;
        });
      })
    );

    await Promise.all(
      allFilePaths.map(async (file) => {
        await fsPromises.unlink(file);
      })
    );

    return true;
  } catch (error) {
    return false;
  }
}

exports.GetListOfEstimates = GetListOfEstimates;
exports.DeleteAllEms = DeleteAllEms;
