import { hideMenus, modalNotifier } from "./evts.js";

function editConf(config = false) {

  
    //check if user is authenticated and configFilesArray is decryptable


    if (config) {
      loadConfig(config);
      return;
    }
    //reset page and event listeners

    hideMenus();

    let outputDiv = document.getElementById("output");
    let submitContainerDiv = document.getElementById("submitContainer");
    let sidebarDiv = document.getElementById("sidebar");
  
    outputDiv.innerHTML = "";
    outputDiv.setAttribute("style", "margin-left: 300px")
    outputDiv.replaceWith(outputDiv.cloneNode(true));

    submitContainerDiv.innerHTML = "";
    submitContainerDiv.style.display = 'block';
    submitContainerDiv.setAttribute("style", "margin-left: 300px")
    submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
    sidebarDiv.innerHTML = "";
    sidebarDiv.style.display = 'block';
    sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));

    document.getElementById("output").appendChild(editConfInput());
    loadConfSidebar();

    //add events
    if (!config) formEvts();
  }

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

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        let confFiles = JSON.parse(this.responseText);
        for (let config of confFiles) {
            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-item";
            sidebarListItem.setAttribute("data-config", config);
            sidebarListItem.innerHTML = config;
            sidebarList.appendChild(sidebarListItem);
        }
        document.getElementById("sidebar").appendChild(sidebarList);
      }
    }
    xhttp.open("GET", "php/index.php/editConf/showAll", true);
    xhttp.send();

  }

  function editConfInput() {
  
    let editConfDisplay = document.createElement("DIV");
    editConfDisplay.classList.add(
      "w3-row-padding",
      "w3-padding-24",
      "w3-container",
      "w3-flat-clouds"
    );
    editConfDisplay.id = "editConfDisplayWrapper";


    //start building submitContainer with save and filename


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

    let saveButton = document.createElement("input");
    saveButton.setAttribute("type", "submit");
    saveButton.setAttribute("value", "Save");
    saveButton.classList.add("w3-button");
    saveButton.classList.add("w3-grey");
    saveButton.style.margin = "20px";
    document.getElementById("submitContainer").appendChild(saveButton);
  
    
  
    let divContainer = document.createElement("DIV");
    divContainer.classList.add("w3-container", "w3-center");

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

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



    let textarea = document.createElement("textarea");
    textarea.setAttribute("name", "configInput");
    textarea.setAttribute("id", "configInput");
    textarea.setAttribute("cols", "100");
    textarea.setAttribute("rows", "30");
    textarea.classList.add("w3-input");


    div.appendChild(textarea);
    divContainer.appendChild(div);


    editConfDisplay.appendChild(divContainer);
    return editConfDisplay;

  }


  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":
                let fileName;
                let userFileNameField = document.getElementById("userFileName");
                let userFileName = userFileNameField.value;
                let userFileNamePH = userFileNameField.getAttribute("placeholder");
                if (userFileName.length != 0) {
                    fileName = userFileName;
                  //clear old data as file switches to new filename
                } else if (userFileNamePH.length != 0) {
                  fileName = userFileNamePH;
                } 
                let data = document.getElementById("configInput").value;
                saveConf(fileName, data);
                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;
        }
      }
    });
    document.getElementById("sidebar").addEventListener("click", (e) => {
        if (e.target && e.target.matches("li.w3-bar-item")) {
          let config = e.target.dataset.config;
          editConf(config);
        }
      });
  }



  function userFileNameDiv() {
    let divContainer = document.createElement("DIV");
    divContainer.classList.add("w3-third", "w3-container");
    divContainer.setAttribute("style", "padding: 0px");
    let div = document.createElement("DIV");
    div.classList.add("w3-section", "w3-flat-silver", "w3-margin-left");
    div.setAttribute("style", "padding: 5px");
    let userFileNameInput = document.createElement("input");
    userFileNameInput.setAttribute("type", "text");
    userFileNameInput.setAttribute("name", "userFileName");
    userFileNameInput.setAttribute("placeholder", "Enter a filename");
    userFileNameInput.classList.add("w3-input");
    userFileNameInput.id = "userFileName";
    div.appendChild(userFileNameInput);
    divContainer.appendChild(div);
    return divContainer;
  }

  function saveConf(fileName, data) {
    let obj = {
      fileName: fileName,
      data: data,
    };
    console.log(obj);
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "php/?setconfig");
    xhttp.setRequestHeader("Accept", "application/json");
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        modalNotifier(this.responseText, 3);
      }
    };
  
    xhttp.send(JSON.stringify(obj));
  }

  function loadConfig(name) {

    document.getElementById("userFileName").setAttribute("placeholder", name);

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("configInput").value = this.responseText;
      }
    }
    xhttp.open("GET", "php/index.php/editConf/"+name, true);
    xhttp.send();
  }

export default editConf;