import {
  storeData,
  clearData,
  retrieveData,
} from "./storage.js";
import { loadTemplate } from "./web.js";
import parseFormOnSubmit from "./parseForm.js";
import { modalNotifier, resetNavBar } from "./evts.js";
import { passwordHash } from "./scripts.js";

function buildFile() {

  //set current page value in activeState object
  activeState.activePage = "files";

  //set templateFiles array
  let tF = retrieveData("templateFiles");

  if (tF == null || tF.length == 0) {
    //console.log("none yet");
    modalNotifier("there are no saved texts yet", activeState.settings.notifierPause);
    return;
  }

  if (screen.width > 992) {
    document.getElementById("siteTitle").innerHTML = "Saved files";
  } else {
    document.getElementById("siteTitle").innerHTML = "TG";
    document.getElementById("logo").innerHTML = "TG";
  }

  //sessionVerfication check
  if (!passwordHash.verify()) {
    modalNotifier("Error: Session is not authenticated...", 0, false);
  }

  //disable toggleFiles Button
  let target = document.getElementById("toggleFilesMenu");
  target.innerHTML = "";
  let i = document.createElement("i");
  i.classList.add("fa", "fa-file");
  //target.classList.add("w3-disabled");
  target.appendChild(i);
  target.style.cssText = 'background-color:#9e9e9e !important';
  target.style.borderBottom = "4px solid #9e9e9e";

  //disable toggleTestBlocksMenu
  document.getElementById("toggleTestBlocksMenu").style.display = "none";

  //reset page and event listeners
  let mainFormDiv = document.getElementById("mainForm");
  let outputDiv = document.getElementById("output");
  let submitContainerDiv = document.getElementById("submitContainer");
  let sidebarDiv = document.getElementById("sidebar");
  let fileInfoDiv = document.getElementById("outputInfo");

  mainFormDiv.innerHTML = "";
  mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
  outputDiv.innerHTML = "";
  outputDiv.replaceWith(outputDiv.cloneNode(true));
  submitContainerDiv.innerHTML = "";
  submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
  sidebarDiv.innerHTML = "";
  sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));
  fileInfoDiv.innerHTML = "";
  fileInfoDiv.replaceWith(fileInfoDiv.cloneNode(true));

  document.getElementById("mainForm").innerHTML = mainFormPlaceholder();

  document.getElementById("sidebar").appendChild(loadFileSidebar(tF));
  document.getElementById("sidebar").addEventListener("click", (e) => {
    if (e.target && e.target.matches("li.w3-bar-item")) {
      let fileName = e.target.dataset.file;
      let template = e.target.dataset.template;
      let pos = e.target.dataset.tfpos;
      clickLoadFileDiv(fileName, template, pos);
    }
  });
}

function loadFileDiv(fileName, template, pos) {
  activeState.fileName = fileName;
  activeState.loadedTemplate = template;

  storeData("userInputForce", retrieveData(fileName, template));

  loadTemplate(template, false, true);

  //append TS info
  let fileInfoDiv = document.getElementById("outputInfo");
  let tF = retrieveData("templateFiles");

  let ts = tF[pos].metadata.ts_create;
  ts = ts.current_time_long+"  "+ts.current_date+"."+ts.current_year;
  fileInfoDiv.innerHTML = "<p>created at: "+ts+" | template: "+template+"</p>";
  fileInfoDiv.style.display = "block";
  
}

function loadFileDivCallBack() {
  let tF = retrieveData("templateFiles");
  document.getElementById("sidebar").appendChild(loadFileSidebar(tF));

  let lT = activeState.loadedTemplate;
  let fN = activeState.fileName;
  let storageName = fN + "_m21_" + lT;

  let fileDisplay = document.createElement("DIV");
  fileDisplay.classList.add(
    "w3-row-padding",
    "w3-padding-24",
    "w3-container",
    "w3-flat-clouds"
  );
  fileDisplay.id = "fileDisplayWrapper";

  //start building submitContainer with edit copy and delete
  let editButton = document.createElement("input");
  editButton.setAttribute("type", "submit");
  editButton.setAttribute("value", "Edit");
  editButton.classList.add("w3-button");
  editButton.classList.add("w3-grey");
  document.getElementById("submitContainer").appendChild(editButton);

  document
    .getElementById("submitContainer")
    .appendChild(document.createTextNode(" "));

  let copyButton = document.createElement("input");
  copyButton.setAttribute("type", "submit");
  copyButton.setAttribute("value", "Copy");
  copyButton.classList.add("w3-button");
  copyButton.classList.add("w3-grey");
  document.getElementById("submitContainer").appendChild(copyButton);

  document
    .getElementById("submitContainer")
    .appendChild(document.createTextNode(" "));

  let deleteButton = document.createElement("input");
  deleteButton.setAttribute("type", "submit");
  deleteButton.setAttribute("value", "Delete");
  deleteButton.classList.add("w3-button");
  deleteButton.classList.add("w3-flat-pomegranate");
  document.getElementById("submitContainer").appendChild(deleteButton);

  if (screen.width > 992) {
    document.getElementById("siteTitle").innerHTML = lT.replace(/_/g, " ");
  } else {
    document.getElementById("siteTitle").innerHTML = "TG";
  }

  let title = document.createElement("div");
  title.classList.add("w3-panel");
  let titleText = document.createElement("h2");
  titleText.innerText = fN.replace(/_/g, " ");
  titleText.style.margin = "0px";
  title.appendChild(titleText);
  fileDisplay.appendChild(title);

  let div = document.createElement("div");
  let parsedTemplate = parseFormOnSubmit(false, true);
  div.appendChild(parsedTemplate);

  fileDisplay.appendChild(div);

  let ts = document.createElement("p");
  ts.innerHTML = ""

  //fileDisplay.appendChild(ts);
  document.getElementById("mainForm").appendChild(fileDisplay);

  //fix min height of file display
  try {
    document.getElementById("fileDisplay").style.cssText = "min-height: 300px;";
  } catch (e) {}
  //fix fontsize for display
  try {
    document.getElementById("fileDisplay").firstChild.style.fontSize = "1em";
  } catch (e) {}
  //add events
  formEvts(storageName);
}

function clickLoadFileDiv(fileName, template, pos) {
  if (fileName == "_overflow") return;

  if (fileName == "_clearAll") {
    clickClearAllFiles();
    return;
  }

  document.getElementById("mainForm").innerHTML = "";
  loadFileDiv(fileName, template, pos);
}

function clearFileData(storData) {
  let fileName = storData.split("_m21_")[0];

  let tF = retrieveData("templateFiles");
  let newArray = [];
  for (let obj of tF) {
    if (obj.fileName != fileName) {
      newArray.push(obj);
    }
  }
  storeData("templateFiles", newArray);

  clearData(fileName);
  clearData("userInput");

  document.getElementById("mainForm").innerHTML = "";
  document.getElementById("output").innerHTML = "";
  document.getElementById("submitContainer").innerHTML = "";
  document.getElementById("sidebar").innerHTML = "";
  document.getElementById("mainForm").innerHTML = mainFormPlaceholder();
  document.getElementById("sidebar").appendChild(loadFileSidebar(newArray));
}

function loadFileSidebar(tF) {
  let sidebarList = document.createElement("ul");
  sidebarList.classList.add("w3-ul");

  let sidebarListItem = document.createElement("li");

  sidebarListItem.classList.add(
      "w3-padding-large",
  );
  sidebarListItem.style.borderBottom = "1px solid #ddd";
  sidebarListItem.id = "sb-title";
  sidebarListItem.innerHTML = "Saved Files:"
  sidebarList.appendChild(sidebarListItem);

  let c = 0;
  let sidebarItemsAmount = 10;
  for (let obj of tF.reverse()) {
    sidebarListItem = document.createElement("li");
    sidebarListItem.classList.add(
      "w3-bar-item",
      "w3-padding-large",
      "w3-button"
    );
    sidebarListItem.style.borderBottom = "1px solid #ddd";
    sidebarListItem.id = "sb-" + obj.fileName.replace(/:/g, "_");

    //handle to many files on screen and display hidden files amount
    if (c > sidebarItemsAmount) {
      sidebarListItem.setAttribute("data-template", "_overflow");
      sidebarListItem.setAttribute("data-file", "_overflow");
      sidebarListItem.style.backgroundColor = "#e3e7e8";
      sidebarListItem.classList.remove("w3-button");
      sidebarListItem.style.borderTop = "1px solid rgb(221, 221, 221)";
      sidebarListItem.innerHTML =
        tF.length - sidebarItemsAmount + " files not shown";
      sidebarList.appendChild(sidebarListItem);
      break;
    }
    sidebarListItem.innerHTML = obj.fileName.replace(/_/g, " ");
    sidebarListItem.setAttribute("data-file", obj.fileName);
    sidebarListItem.setAttribute("data-template", obj.template);
    sidebarListItem.setAttribute("data-tFPos", obj.pos);
    sidebarList.appendChild(sidebarListItem);
    c++;
  }

  //clear all files button
  sidebarListItem = document.createElement("li");
  sidebarListItem.classList.add("w3-bar-item", "w3-padding-large", "w3-button");
  sidebarListItem.setAttribute("data-template", "_clearAll");
  sidebarListItem.setAttribute("data-file", "_clearAll");
  sidebarListItem.classList.add("w3-hover-flat-pomegranate", "w3-bottom");
  sidebarListItem.style.borderTop = "1px solid rgb(221, 221, 221)";
  sidebarListItem.style.width = "300px";
  sidebarListItem.innerHTML = "Clear all files";
  sidebarList.appendChild(sidebarListItem);

  return sidebarList;
}

function mainFormPlaceholder(msg = "Select a file") {
  return (
    "<div id='fileDisplay' class='w3-row-padding w3-padding-24 w3-container w3-flat-clouds'><div class='w3-code notranslate w3-border-white' style='font-family: Arial, Helvetica, sans-serif;'><p>" +
    msg +
    "</p><br><br><br><br><br><br><br><br><br><br><br></div></div>"
  );
}

function copyFileToClipboard() {
  const fileDisplay = document.getElementById("fileDisplay");
  if (fileDisplay != null) {
    copyToClipBoard(fileDisplay.innerHTML);
  } else {
    console.log("error file not found");
  }
}

function copyToClipBoard(html) {
  // Create an iframe (isolated container) for the HTML
  var container = document.createElement("div");
  container.innerHTML = html;

  // Hide element
  container.style.position = "fixed";
  container.style.pointerEvents = "none";
  container.style.opacity = 0;

  // Detect all style sheets of the page
  var activeSheets = Array.prototype.slice
    .call(document.styleSheets)
    .filter(function (sheet) {
      return !sheet.disabled;
    });

  // Mount the iframe to the DOM to make `contentWindow` available
  document.body.appendChild(container);

  // Copy to clipboard
  window.getSelection().removeAllRanges();

  var range = document.createRange();
  range.selectNode(container);
  window.getSelection().addRange(range);

  document.execCommand("copy");
  for (var i = 0; i < activeSheets.length; i++) activeSheets[i].disabled = true;
  document.execCommand("copy");
  for (var i = 0; i < activeSheets.length; i++)
    activeSheets[i].disabled = false;

  // Remove the iframe
  document.body.removeChild(container);
}

function formEvts(storageName) {
  //add event listener to submitContainer
  document.getElementById("submitContainer").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "INPUT") {
      switch (e.target.value) {
        case "Edit":
          editSpecificTemplate(storageName);
          break;
        case "Copy":
          copyFileToClipboard();
          e.target.className = e.target.className.replace(
            " w3-grey",
            " w3-flat-carrot"
          );
          e.target.style.pointerEvents = "none";
          const timeoutCopy = setTimeout(() => {
            e.target.className = e.target.className.replace(
              " w3-flat-carrot",
              " w3-grey"
            );
            e.target.style.pointerEvents = "auto";
          }, 250);
          modalNotifier(activeState.fileName + " copied to clipboard", activeState.settings.notifierPause);
          break;
        case "Delete":
          console.log(storageName);
          let previousFile = getPreviousFile(storageName);
          clearFileData(storageName);
          let delFileName = activeState.fileName;
          document.getElementById("mainForm").innerHTML = "";
          if (previousFile) {
            loadFileDiv(previousFile.fileName, previousFile.template, previousFile.pos);
          } else {
            document.getElementById("mainForm").innerHTML =
              mainFormPlaceholder("No file yet");
          }
          modalNotifier(delFileName + " deleted!", activeState.settings.notifierPause);

          break;
        default:
          e.preventDefault;
      }
    }
  });
}

function editSpecificTemplate(storageName) {
  storeData(
    "userInputForce",
    retrieveData(storageName.split("_m21_")[0], storageName.split("_m21_")[1])
  );
  //reset sidebar to clear events
  let sidebarDiv = document.getElementById("sidebar");
  sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));

  //reset navbar above all else
  resetNavBar();

  //reset correct activePage
  activeState.activePage = "template";

  loadTemplate(storageName.split("_m21_")[1]);
}

function getPreviousFile(storageName) {
  let orgFileName = storageName.split("_m21_")[0];
  let tF = retrieveData("templateFiles");
  let i = 0;
  let previousFile;

  for (let obj of tF) {
    if (obj.fileName == orgFileName) {
      previousFile = tF[i - 1];
      if (previousFile === undefined) {
        //get the next one if there is no previous one
        previousFile = tF[i + 1];
      }
      break;
    }
    i++;
  }

  return previousFile != undefined ? previousFile : false;
}

function clickClearAllFiles() {
  let modal = document.getElementById("modalMsg");
  modal.replaceWith(modal.cloneNode(true));
  document.getElementById("modalMsg").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "BUTTON") {
      let modal = document.getElementById("modalNotifier");
      switch (e.target.innerHTML) {
        case "Delete":
          clearAllFiles();
          modal.replaceWith(modal.cloneNode(true));
          modalNotifier("All files deleted!", activeState.settings.notifierPause);
          break;
        default:
          e.preventDefault;
      }
    }
  });
  modalNotifier(
    "<div class='w3-container'> \
    <p>Would you really like to delete all stored files?</p> \
    <button class='w3-button w3-border w3-flat-pomegranate' >Delete</button>",
    0
  );
}
function clearAllFiles() {
  let tF = retrieveData("templateFiles");
  if (tF == null || tF.length == 0) {
    modalNotifier("there are no saved texts yet", activeState.settings.notifierPause);
    return;
  }
  for (let storageName of tF) {
    clearFileData(storageName.fileName);
  }
}

export { buildFile, loadFileDivCallBack };
