import {
  clearData,
  createStorageObj,
  createBookShelf,
  importBookShelf,
} from "./storage.js";
import {
  loadTemplate,
  storeFilesToServer,
  setTemplatePreset,
  checkForStoredDataOnServer,
  delStoredDataOnServer
} from "./web.js";
import parseFormOnSubmit from "./parseForm.js";
import { getUsrId } from "./scripts.js";

function showMenu() {
  var x = document.getElementById("navMob");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }

  if (screen.width < 993) {
    let sidebar = document.getElementById("sidebar");
    sidebar.style.display = "none";
  }
}
function showSidebar() {
  let sidebar = document.getElementById("sidebar");
  if (getComputedStyle(sidebar).display === "none") {
    sidebar.style.display = "block";
    sidebar.style.marginTop = "35px";
  } else {
    sidebar.style.display = "none";
  }

  if (screen.width < 993) {
    let navBar = document.getElementById("navMob");
    navBar.className = navBar.className.replace(" w3-show", "");
  }
}

function showTextBlocks() {
  var x = document.getElementById("navTb");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }

  if (screen.width < 993) {
    let sidebar = document.getElementById("sidebar");
    sidebar.style.display = "none";
  }
}

function insertTextBlocks(t) {
  let insert = "!" + t.innerText.split(":")[0] + " ";
  let id = activeState.lastElement;
  let element = document.getElementById(id);
  if (element === null) {
    return;
  }
  element.value += insert;
  let tB = document.getElementById("navTb");
  tB.className.replace(" w3-show", "");
  element.focus();
}

function handleOnBlur(t) {
  activeState.lastElement = t.id;
  createStorageObj();
}

function clickClearForm() {
  //document.activeElement.blur();
  //document.getElementById("sidebar").focus();
  clearData("userInput");
  let lT = activeState.loadedTemplate;
  loadTemplate(lT);
}

function hideMenus() {
  let sidebar = document.getElementById("sidebar");
  sidebar.style.display = "none";
  let navBar = document.getElementById("navMob");
  navBar.className = navBar.className.replace(" w3-show", "");
  let tbBar = document.getElementById("navTb");
  tbBar.className = tbBar.className.replace(" w3-show", "");
}

function modalNotifier(msg, timeout) {
  let modalElement = document.getElementById("modalNotifier");
  let msgElement = document.getElementById("modalMsg");

  modalElement.style.display = "block";
  msgElement.innerHTML = msg;
  if (timeout === undefined) {
    const run = setTimeout(() => (modalElement.style.display = "none"), 5000);
  } else if (timeout >= 1) {
    const run = setTimeout(
      () => (modalElement.style.display = "none"),
      timeout * 1000
    );
  }
}

function clickSetForm(e) {
  e.preventDefault;
  let dataArray = parseFormOnSubmit(true);
  let lT = activeState.loadedTemplate;
  setTemplatePreset(lT, JSON.stringify(dataArray));
  modalNotifier("Form Saved", 2);
}

function clickImportFiles() {
  if (activeState.localOnly) {
    createBookShelfDownload();
    return;
  }
  checkForStoredDataOnServer();
  document.getElementById("modalMsg").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "BUTTON") {
      let modal = document.getElementById("modalNotifier");
      switch (e.target.innerHTML) {
        case "Import":
          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 "Yes":
                  importBookShelf();
                  modal.replaceWith(modal.cloneNode(true));
                  modalNotifier("Imported!", 2);
                  break;
                case "Cancel":
                  modal.replaceWith(modal.cloneNode(true));
                  document.getElementById("modalNotifier").style.display = "none";
                  break;
                default:
                  e.preventDefault;
              }
            }
          })
          modalNotifier(
            "<div class='w3-container'> \
            Would you like to import the backup created on: "+activeState.serverFilesTs.replace("_", " - ")+ "<br><br> \
            <button class='w3-button w3-border w3-flat-wet-asphalt' >Yes</button> \
            <button class='w3-button w3-border w3-flat-wet-asphalt' >Cancel</button></div>",
          0);
          break;
        case "Save":
          storeFilesToServer(createBookShelf());
          modal.replaceWith(modal.cloneNode(true));
          modalNotifier(
            "Files saved to server <br><br> would you like to <a href='/storage/" +
              getUsrId() +
              ".txt' style='text-decoration: underline;' download>download</a> them?"
          ,0);
          break;
        case "Delete":
          delStoredDataOnServer();
          break;

        default:
          e.preventDefault;
      }
    }
  });
  modalNotifier(
    "Here you can manage if your files should be saved on the server \
    <br> If there are stored files already on the server you can inport them \
    It will overwrite any saved documents <br><br> \
    <div class='w3-container'> \
    <button style='display: none;' id='importModalBtn' class='w3-button w3-border w3-flat-wet-asphalt' >Import</button> \
    <button class='w3-button w3-border w3-flat-wet-asphalt' >Save</button> \
    <button class='w3-button w3-border w3-flat-pomegranate' >Delete</button></div>", 
  0);

}

function createBookShelfDownload() {
  let data = createBookShelf();
  let filename = data[0]['data'] + ".txt";
  document.getElementById("modalMsg").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "BUTTON") {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)));
      element.setAttribute('download', filename);
      element.style.display = 'none';
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    }
  });
  modalNotifier(
    "Since you are in local only mode you can only export a backup of your files \
    <br><br> \
    <div class='w3-container'> \
    <button class='w3-button w3-border w3-flat-wet-asphalt' >Export</button></div>"
  ,0);

}

export {
  hideMenus,
  showMenu,
  showSidebar,
  showTextBlocks,
  insertTextBlocks,
  handleOnBlur,
  clickClearForm,
  modalNotifier,
  clickSetForm,
  clickImportFiles
};
