import buildForm from "./form.js";
import { loadFileDivCallBack } from "./files.js";
import { retrieveData, clearData, getFileName, importBookShelf } from "./storage.js";
import { insertTextBlocks, modalNotifier } from "./evts.js";
import { createTemplate, createTemplateCallBack} from "./createTemplate.js";
import { getUsrId, sessionVerification } from "./scripts.js";

function loadTemplate(template, newFlag = false, loadOnly = false) {
  document.getElementById("siteTitle").innerHTML = template.replace(/_/g, " ");
  activeState.loadedTemplate = template;

  if (newFlag) {
    activeState.fileName = "none";
  } else {
    activeState.fileName = getFileName();
  }

  document.getElementById("navMob").className = document
    .getElementById("navMob")
    .className.replace(" w3-show", "");
  if (screen.width < 993) {
    let sidebar = document.getElementById("sidebar");
    sidebar.style.display = "none";
    document.getElementById("siteTitle").innerHTML = "TG";
  }
  var xhttp = new XMLHttpRequest(); 
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let respText = decodeURIComponent(this.responseText);
      if (loadOnly == "createTemplate") {
        createTemplateCallBack(template, respText.split("!JSON_placeholder:")[0]);         
        return;
      }
      buildForm(respText, loadOnly);
      if (loadOnly) {
        loadFileDivCallBack();
        return;
      }

      //retrieve previos userData / or preset data if newFile is called
      let cdata;
      if (newFlag) {
        cdata = retrieveData("templatePreset", template);
      } else {
        cdata = retrieveData("userInputForce");
      }
      if (cdata != "") {
        let res = "";
        try {
          res = JSON.parse(cdata);
        } catch (e) {
          console.log("error", cdata);
          return;
        }
        retrieveForm(res);
      }

      //select first object and focus on it
      let obj = JSON.parse(
        window.sessionStorage.getItem("templateObjectsPurified")
      );
      let firstElement = document.getElementById(obj[0].word.replace(/ /g, "_"));
      if (firstElement != null) firstElement.focus();
      
    }
  };
  xhttp.open("GET", "php/?template=" + template, true);
  xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhttp.send();
}

function loadNewTemplate(template) {

  //sessionVerfication check
  if (!sessionVerification()) {
    modalNotifier("Error: Session is not authenticated...", 0);
  }
  
  //set current page value in activeState object
  activeState.activePage = "template";

  let sidebarDiv = document.getElementById("sidebar");
  sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));

  clearData("userInput", template);
  loadTemplate(template, true);
}

function loadNavBar() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let res = "";
      try {
        res = JSON.parse(this.responseText);
      } catch (e) {
        console.log("error", this.responseText);
        return;
      }
      
      let divMob = document.getElementById("navMob");
      for (let x in res) {
        let aMob = document.createElement("a");

        aMob.setAttribute("href", "#");
        aMob.setAttribute("data-template", res[x][1]);
        aMob.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
        aMob.innerHTML = res[x][0];

        divMob.appendChild(aMob);

        activeState.templates.push(res[x][1]);
      }
      let createEntry = document.createElement("a");
      createEntry.setAttribute("href", "#");
      createEntry.setAttribute("data-template", "createNew");
      createEntry.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
      createEntry.innerHTML = "Manage templates";

      divMob.appendChild(createEntry);
      divMob.addEventListener("click", (e) => {
        if (e.target && e.target.matches("a.w3-bar-item")) {
          let template = e.target.dataset.template;
          if (template == "createNew") {
            createTemplate();
            return;
          }
          loadNewTemplate(template);
        }
      });
    }
  };
  xhttp.open("GET", "php/?templates", true);
  xhttp.send();
}
function initTextBlocks() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let res = "";
      try {
        res = JSON.parse(this.responseText);
      } catch (e) {
        console.log("error", this.responseText)
        return;
      }
      const textBlocksHolder = document.getElementById("textBlocks");
      const divReg = document.getElementById("navTb");
      for (let x in res) {
        if (res[x][1].length < 1) continue;

        let aReg = document.createElement("a");
        aReg.setAttribute("href", "#");
        aReg.classList.add("w3-bar-item", "w3-hide-small", "w3-padding-small");
        let textBlockText = res[x][1];
        if (res[x][1].length > 80) {
          textBlockText = res[x][1].substr(0, 80) + "...";
        }
        aReg.innerHTML = "<b>" + res[x][0] + ":</b> " + textBlockText;
        divReg.appendChild(aReg);

        const text = document.createTextNode(
          res[x][0] + ": " + res[x][1] + "\n"
        );
        textBlocksHolder.appendChild(text);
      }
      divReg.addEventListener("click", (e) => {
        if (e.target && e.target.matches("a.w3-bar-item")) {
          insertTextBlocks(e.target);
        }
      });
    }
  };
  xhttp.open("GET", "php/?textBlocks", true);
  xhttp.send();
}

function setTemplatePreset(template, formData) {
  //console.log(template +" : "+ formData);
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "php/?setForm");
  xhttp.setRequestHeader("Accept", "application/json");
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      //console.log(this.responseText);
    }
  };
  let data = {
    template: template,
    data: formData,
  };

  xhttp.send(JSON.stringify(data));
}

function setNewTemplate(fileName, data) {
  let obj = {
    fileName: fileName,
    data: data,
  };
  //console.log(template +" : "+ formData);
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "php/?setTemplate");
  xhttp.setRequestHeader("Accept", "application/json");
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      //console.log(this.responseText);
    }
  };

  xhttp.send(JSON.stringify(obj));
}

function storeFilesToServer(data) {
  //console.log(template +" : "+ formData);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      if (this.responseText == "success") {
        console.log("files saved");
      }
    }
  };
  xhttp.open("POST", "php/?storeFiles", true);
  xhttp.setRequestHeader("Accept", "application/json");
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.send(JSON.stringify(data));
}

function checkForStoredDataOnServer() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      if (this.responseText == "none") {
      } else {
        activeState.serverFilesTs = this.responseText;
        let btn = document.getElementById("importModalBtn");
        btn.style.display = "";
      }
    }
  };
  xhttp.open("GET", "php/?storedFiles="+getUsrId(), true);
  xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhttp.send();
}

function delStoredDataOnServer() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      if (this.responseText == "none") {
        let btn = document.getElementById("importModalBtn");
        btn.style.display = "none";
      } 
    }
  };
  xhttp.open("GET", "php/?storedFiles="+getUsrId()+"&del", true);
  xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhttp.send();
}


function retrieveForm(arr) {
  for (let i = 0; i < arr.length; i++) {
    let e = document.getElementById(arr[i].name);
    if (e === null) {
      e = document.getElementById(arr[i].name.split("cl-")[1]);
      if (e === null) continue;
    }

    if (e.name.substr(0, 4) == "clM-") continue;

    switch (e.nodeName) {
      case "TEXTAREA":
        e.innerHTML = arr[i].value;
        break;
      case "INPUT":
        e.value = arr[i].value;
        break;
      case "SELECT":
        for (let j = 0; j < e.options.length; j++) {
          if (e.options[j].value == arr[i].value) {
            // Item is found. Set its property and exit
            e.options[j].selected = true;
            break;
          }
        }
        break;
      default:
        e.innerHTML = arr[i].value;
        break;
    }
  }
}
export {
  loadTemplate,
  loadNavBar,
  initTextBlocks,
  loadNewTemplate,
  setTemplatePreset,
  setNewTemplate,
  storeFilesToServer,
  checkForStoredDataOnServer,
  delStoredDataOnServer
};
