import {
  storeData,
  clearData,
  retrieveData,
  createStorageObj,
} from "./storage.js";
import { loadTemplate } from "./web.js";
import parseFormOnSubmit from "./parseForm.js";

function buildFile() {
  createStorageObj();


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

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

  if (tF == null) {
    //console.log("none yet");
    alert("there are no saved texts yet");
    return;
  }

  if (screen.width > 992) {
    document.getElementById("siteTitle").innerHTML = "Template Gen";
  } else {
    document.getElementById("siteTitle").innerHTML = "TG";
  }

  //hide set Form button
  document.getElementById("setFormButton").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");

  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));

  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;
      clickLoadFileDiv(fileName, template);
    }
  });
}

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

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

  loadTemplate(template, false, true);
}

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

  let lT = activeState.loadedTemplate;
  let fN = activeState.fileName;
  let storageName = fN + "-" + 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-red");
  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");
  div.appendChild(parseFormOnSubmit(false, true));
  fileDisplay.appendChild(div);
  document.getElementById("mainForm").appendChild(fileDisplay);

  //add events
  formEvts(storageName);
}

function clickLoadFileDiv(fileName, template) {
  document.getElementById("mainForm").innerHTML = "";
  loadFileDiv(fileName, template);
}

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

  let tF = JSON.parse(retrieveData("templateFiles"));
  let newArray = [];
  for (let obj of tF) {
    if (obj.fileName != fileName) {
      newArray.push(obj);
    }
  }
  storeData("templateFiles", JSON.stringify(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 c = 0;
  let sidebarItemsAmount = 10;
  for (let obj of tF) {
    let 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, "_");

    if (c > sidebarItemsAmount) {
      sidebarListItem.setAttribute("data-template", '_overflow');
      sidebarListItem.setAttribute("data-file", '_overflow');
      sidebarListItem.innerHTML = templates.length - sidebarItemsAmount + " files not shown";
      sidebarList.appendChild(sidebarListItem);
      return sidebarList;
    }
    sidebarListItem.innerHTML =
      obj.fileName.replace(/_/g, " ") + " - " + obj.template.replace(/_/g, " ");
    sidebarListItem.setAttribute("data-file", obj.fileName);
    sidebarListItem.setAttribute("data-template", obj.template);
    sidebarList.appendChild(sidebarListItem);
  }
  return sidebarList;
}

function mainFormPlaceholder(msg = "Select a file") {
  return "<div 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":
          loadSpecificTemplate(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);
          break;
        case "Delete":
          let previousFile = getPreviousFile(storageName);
          clearFileData(storageName);
          document.getElementById("mainForm").innerHTML = "";
          if (previousFile) {
            loadFileDiv(previousFile.fileName, previousFile.template);
          } else {
            document.getElementById("mainForm").innerHTML = mainFormPlaceholder("No file yet");
          }

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

function loadSpecificTemplate(storageName) {
  storeData(
    "userInputForce",
    retrieveData(storageName.split("-")[0], storageName.split("-")[1])
  );
  loadTemplate(storageName.split("-")[1]);
}

function getPreviousFile(storageName) {

  let orgFileName = storageName.split("-")[0];
  let tF = JSON.parse(retrieveData("templateFiles"));
  let i = 0;
  let previousFile;

  for (let obj of tF) {
    if (obj.fileName == orgFileName) {
      previousFile = tF[i-1];
      break;
    }
    i++;
  }

  return (previousFile != undefined) ?  previousFile : false;
}

export { buildFile, loadFileDivCallBack };
