import { hideMenus, modalNotifier, printVersion, resetNavBar } from "./evts.js";
import { passwordHash, sanitize } from "./scripts.js";
import { clearData, retrieveData, storeData, storeSettings } from "./storage.js";

const buildSettings = () => {
  //set current page value in activeState object
  activeState.activePage = "settings";

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

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

  //reset navbar if files was used
  resetNavBar();

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

  //reset page and event listeners

  hideMenus("force");

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

  addSidebar();

  buildForm();

  //add events
  formEvts();
};

function formEvts() {
  //add event listener to submitContainer
  document.getElementById("submitContainer").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "INPUT") {
      switch (e.target.value) {
        case "Save":
          saveSettings();
          modalNotifier(
            "Settings saved!",
            activeState.settings.notifierPause
          );
          e.target.className = e.target.className.replace(
            " w3-grey",
            " w3-flat-nephritis"
          );
          e.target.style.pointerEvents = "none";
          const timeoutSave = setTimeout(() => {
            e.target.className = e.target.className.replace(
              " w3-flat-nephritis",
              " w3-grey"
            );
            e.target.style.pointerEvents = "auto";
          }, 250);
          e.preventDefault;
          break;
        default:
          e.preventDefault;
      }
    }
  });
}


function buildForm() {
  let form = document.createElement("FORM");
  form.setAttribute("method", "post");
  form.setAttribute("action", "javascript:void(0)");
  form.setAttribute("id", "mainFormObj");
  form.classList.add("w3-row");

  let settings = storeSettings("get", true);
  if (settings == "") settings = activeState.settings; 

  for (let setting of Object.entries(settings)) {
    buildField(setting, form);
  }

  //add form to mainForm Div
  document.getElementById("mainForm").appendChild(form);

  // create a Save button
  let saveBtn = document.createElement("input");
  saveBtn.setAttribute("type", "submit");
  saveBtn.setAttribute("value", "Save");
  saveBtn.classList.add("w3-button");
  saveBtn.classList.add("w3-grey");
  saveBtn.style.margin = "20px";
  //append submit button to submitContainer

  document.getElementById("submitContainer").appendChild(saveBtn);
}

function buildField(obj, form) {

  //create template Input fields
  let divContainer = document.createElement("DIV");
  divContainer.classList.add("w3-half");
  divContainer.classList.add("w3-container");

  let div = document.createElement("DIV");
  div.classList.add("w3-section");
  div.classList.add("w3-left-align");

  div.setAttribute("style", "padding: 10px");

  let label = document.createElement("LABEL");
  label.style.display = "inline-block";
  label.style.width = "100%";
  label.style.paddingBottom = "5px";
  label.style.borderBottom = "thin solid #9e9e9e";
  label.style.fontWeight = "800";

  let input = document.createElement("input");
  input.setAttribute("type", "text");
  input.setAttribute("name", obj[0]);
  input.setAttribute("id", obj[0]);
  input.classList.add("w3-input");
  input.id = obj[0];
  input.value = obj[1];
  label.innerHTML = obj[0];
  div.appendChild(label);
  div.appendChild(input);
  //append field to wrapper and add to mainForm
  divContainer.appendChild(div);
  form.appendChild(divContainer);
}

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

  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-title";
  sidebarListItem.innerHTML = "Edit Settings"
  sidebarList.appendChild(sidebarListItem);

  document.getElementById("sidebar").appendChild(sidebarList);

}

function saveSettings() {
  let x = document.getElementById("mainFormObj");
  let obj = {};
  if (x == null) {
    return;
  }
  for (let i = 0; i < x.length; i++) {
    let name = x.elements[i].name;
    let value = x.elements[i].value;
    obj[name] = sanitize(value);
  }
  for (let setting of Object.entries(obj)) {
    if (activeState.settings[setting[0]] != setting[1]) {
      //change detected
      if (setting[0] == "persistentStorage") {
        //get tF from old storage
        let tF = retrieveData("templateFiles");
        //get previous settings
        let settings = storeSettings("get", true);
        //store the new settings in old storage
        storeSettings(obj);
        //apply the new setting
        activeState.settings[setting[0]] = setting[1];

        //store the new settings in the new storage
        if (settings != "") storeSettings(obj);
        //transfer tF
        if (tF != null) storeData("templateFiles", tF);

        let msg = (activeState.settings.persistentStorage == "false") ? "temporary" : "persistent";
        printVersion("storage mode: "+msg+" |");

      }
    }
    activeState.settings[setting[0]] = setting[1];
  } 
  storeSettings(obj);
}


export default buildSettings;
