/* eslint-disable no-inner-declarations */
// VLEAPI FOLDER FIXER inner declarations just because so es lint disabled for that rule here
if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
  console.log(
    "Running VLE FOLDER  HELPER OFFLINE - it will ask for a folder when a call is made to VLE.get_folder"
  );
  // overwrite the VLE function which does som dodgy ass crap and replace it with an automatic way of getting the content
  window.VLE.get_folder = function (name, ok, error, t) {
    if (t === undefined) {
      t = this;
    }
    window.VLE.get_folder_callback = function (data) {
      console.log(
        "the callback data that would have been in the file >>>>",
        data
      );
      ok.call(t, data);
    };
    /* Idea is to store the folder info in locahost for re-use */
    if (window.localStorage.getItem("vle-folder-helper")) {
      //  localStorage.clear();
      let resetFolderButton = document.createElement("button");
      resetFolderButton.innerHTML= "📂"
      resetFolderButton.title = "Running from localstorage - clear it";
      resetFolderButton.style.width = "40px";
      resetFolderButton.style.padding = "5px";
      resetFolderButton.style.position = "fixed";
      resetFolderButton.style.top = "0px";
      resetFolderButton.style.right = "0px";
      resetFolderButton.style.whiteSpace = "normal";
      resetFolderButton.addEventListener("click", () => {
        localStorageClear();
      });
      document.body.appendChild(resetFolderButton);
      window.VLE.get_folder_callback(
        JSON.parse(window.localStorage.getItem("vle-folder-helper"))
      );
    } else {
      // request the folder from the user
      ShowStuffForUserInteractionWhichIsNeeded();
    }
  };

  function ShowStuffForUserInteractionWhichIsNeeded() {
    let theButtonThatTriggersTheFolderSearch = document.createElement("button");
    theButtonThatTriggersTheFolderSearch.innerHTML =
      "CLICK HERE TO PICK A FOLDER";
    theButtonThatTriggersTheFolderSearch.style.width = "100%";
    theButtonThatTriggersTheFolderSearch.style.padding = "20px";
    theButtonThatTriggersTheFolderSearch.style.wordWrap = "break-word";
    theButtonThatTriggersTheFolderSearch.style.whiteSpace = "normal";
    theButtonThatTriggersTheFolderSearch.addEventListener("click", () => {
      getContentsOfFolder();
    });

    let theMainHoldingDivForUserInteracton = document.createElement("div");
    theMainHoldingDivForUserInteracton.style.position = "absolute";
    theMainHoldingDivForUserInteracton.style.top = 0;
    theMainHoldingDivForUserInteracton.style.left = 0;
    theMainHoldingDivForUserInteracton.style.bottom = 0;
    theMainHoldingDivForUserInteracton.style.right = 0;
    theMainHoldingDivForUserInteracton.style.padding = "15%";
    theMainHoldingDivForUserInteracton.style.paddingTop = "5%";
    theMainHoldingDivForUserInteracton.style.backgroundColor = "#efefef";
    theMainHoldingDivForUserInteracton.innerHTML = `<h1>Hi</h1>
  <p>You're seeing this because this interactive runs using the vleapi folder helper - when you run the inetractive locally on localhost or 127.0.0.1 it
  will ask for a folder to pull the data from (basically the unzipped version of your attachment zip file) THIS SHOULD BE IN THE SAME FOLDER AS THE INDEX.HTML FILE
 (But you can call it whatever you want and have as many as you want and flip between them with a refresh)
  </p>
  <p>
  You should not have to change existing code to get this to work - it will do some funky stuff to change the functionality of the vleapi's get_folder() function and make it just nicer and easier
  </p>`;

    theMainHoldingDivForUserInteracton.append(
      theButtonThatTriggersTheFolderSearch
    );
    theMainHoldingDivForUserInteracton.id = "NeedFolder";
    document.body.append(theMainHoldingDivForUserInteracton);
  }

  let folderName = null;
  async function getAllContents(directoryHandle, mypath = "") {
    const result = [];
    if (!folderName) {
      folderName = directoryHandle.name;
    }
    let slashpath = "";
    if (mypath) {
      slashpath = mypath + "/";
    }
    for await (const entry of directoryHandle.values()) {
      // console.log("directory", entry);
      if (entry.kind === "directory") {
        const nestedContents = await getAllContents(
          entry,
          slashpath + entry.name
        );
        result.push(...nestedContents);
      } else {
        result.push({
          url: folderName + "/" + slashpath + entry.name,
          path: slashpath + entry.name,
        });
      }
    }

    return result;
  }

  async function getContentsOfFolder() {
    try {
      // eslint-disable-next-line no-undef
      const directoryHandle = await showDirectoryPicker();
      const allContents = await getAllContents(directoryHandle);
      // console.log("All contents of the folder:", allContents);
      window.localStorage.setItem(
        "vle-folder-helper",
        JSON.stringify(allContents)
      );
      window.VLE.get_folder_callback(allContents);
    } catch (error) {
      console.error("Error accessing the directory:", error);
    }

    document.getElementById("NeedFolder").remove();
  }

  function localStorageClear() {
    window.localStorage.setItem("vle-folder-helper" , "");
    window.location.reload();
  }
}
