import {setNewTemplate, loadTemplate} from "./web.js";
import { retrieveData } from "./storage.js";
import { hideMenus, modalNotifier } from "./evts.js";

function createTemplate(template = false) {

  
    //set current page value in activeState object
    activeState.activePage = "createTemplate";
  
    //check if user is authenticated and templateFilesArray is decryptable
    let tF = retrieveData("templateFiles");
    if (tF != "") {
      try {
        tF = JSON.parse(tF);
      } catch (e) {
        alert("Decryption failed; are you authenticated?");
        window.location.reload();
        return;
      }
    }

  
    if (screen.width > 992) {
      document.getElementById("siteTitle").innerHTML = "Manage templates";
    } else {
      document.getElementById("siteTitle").innerHTML = "TG";
    }
  
    //hide set Form button
    document.getElementById("setFormButton").style.display = "none";

    if (template) {
        document.getElementById("templateInput").value = loadTemplate(template, false, "createTemplate");
        return;
    }
  
    //reset page and event listeners

    hideMenus();

    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").appendChild(createTemplateInput());
    document.getElementById("sidebar").appendChild(loadTemplateSidebar(activeState.templates));

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

  function createTemplateCallBack(fileName, data) {

    document.getElementById("templateInput").value = data;
    document.getElementById("userFileName").setAttribute("placeholder", fileName);
  }

  function loadTemplateSidebar(templates) {
    let sidebarList = document.createElement("ul");
    sidebarList.classList.add("w3-ul");
    if (!templates.includes('_textBlocks')) {
      templates.push('_textBlocks');
    }


    for (let template of templates) {
        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-template", template);
        sidebarListItem.innerHTML = template.replace(/_/g, " ");
        sidebarList.appendChild(sidebarListItem);
    }

    return sidebarList;

  }

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


    //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", "templateInput");
    textarea.setAttribute("id", "templateInput");
    textarea.setAttribute("cols", "100");
    textarea.setAttribute("rows", "30");
    textarea.classList.add("w3-input");


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


    createTemplateDisplay.appendChild(divContainer);
    return createTemplateDisplay;

  }


  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("templateInput").value;
                setNewTemplate(fileName, data);
                modalNotifier(fileName+" saved!", 1);
                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 template = e.target.dataset.template;
          createTemplate(template);
        }
      });
  }



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

export {createTemplate, createTemplateCallBack};