import { getFileName } from "./storage.js";

function transformTemplateObject(objects) {
  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 sidebarList = document.createElement("ul");
  sidebarList.classList.add("w3-ul");

  for (let i = 0; i < objects.length; i++) {
    buildField(objects[i], form, sidebarList);
  }

  //console.log(objects);

  //create sidebar submit button
  let sidebarSubmitButton = document.createElement("li");
  sidebarSubmitButton.classList.add(
    "w3-bar-item",
    "w3-padding-large",
    "w3-button"
  );
  sidebarSubmitButton.style.borderTop = "2px solid #ddd";
  sidebarSubmitButton.id = "sb-submit";
  sidebarSubmitButton.innerHTML = "Save & Copy";
  sidebarList.appendChild(sidebarSubmitButton);

  //add sidebar elemnts to sidebar
  document.getElementById("sidebar").appendChild(sidebarList);

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

  //create username and append field to site
  let fileName = getFileName();
  document.getElementById("submitContainer").appendChild(userFileNameDiv(fileName));

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

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

}


function buildField(obj, form, sidebarList) {
  //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-flat-silver");

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

  let label = document.createElement("LABEL");

  let connectedListsArray = [];

  let ltPlaceholder;

  //check for longtext:!li and convert it to standard longText
  if (obj.type.indexOf("longText") !== -1) {
    if (obj.type.indexOf(":") !== -1) {
      ltPlaceholder = obj.type.split(":")[1];
      if (ltPlaceholder !== undefined) {
        let textarea = document.createElement("textarea");
        textarea.setAttribute("name", obj.word.replace(/ /g, "_"));
        textarea.setAttribute("id", obj.word.replace(/ /g, "_"));
        textarea.setAttribute("cols", "100");
        textarea.setAttribute("rows", "15");
        textarea.classList.add("w3-input");
        textarea.id = obj.word.replace(/ /g, "_");
        divContainer.classList.remove("w3-half");
        divContainer.classList.add("w3-center");
        label.innerHTML = obj.word;
        div.appendChild(label);
        div.appendChild(textarea);
      }
    }
  }


  if (obj.type.indexOf("simpleInput") !== -1) {
    if (obj.type.indexOf(":") !== -1) {
      ltPlaceholder = obj.type.split(":")[1];
      if (ltPlaceholder !== undefined) {
        let input = document.createElement("input");
        input.setAttribute("type", "text");
        input.setAttribute("name", obj.word.replace(/ /g, "_"));
        input.setAttribute("id", obj.word.replace(/ /g, "_"));
        input.classList.add("w3-input");
        input.id = obj.word.replace(/ /g, "_");
        label.innerHTML = obj.word;
        div.appendChild(label);
        div.appendChild(input);
      }
    }
  }

  //check for markup:title and display it as none
  if (obj.type.indexOf("markup") !== -1) {
    if (obj.type.indexOf(":") !== -1) {
      ltPlaceholder = obj.type.split(":")[1];
      if (ltPlaceholder !== undefined) {
        divContainer.classList.add("hidden");
        let input = document.createElement("input");
        input.setAttribute("type", "text");
        input.setAttribute("name", obj.word.replace(/ /g, "_"));
        input.id = obj.word.replace(/ /g, "_");
        input.value = obj.word;
        divContainer.style.display = "none";
        label.innerHTML = obj.word;
        div.appendChild(label);
        div.appendChild(input);
      }
    }
  }


  switch (obj.type) {
    case "genderSpecific":
      let select = document.createElement("select");
      select.setAttribute("name", obj.word.replace(/ /g, "_"));
      select.id = obj.word.replace(/ /g, "_");
      select.classList.add("w3-select");
      if (typeof obj.m !== "undefined") {
        let optionM = document.createElement("option");
        optionM.value = obj.m;
        optionM.text = obj.m;
        select.appendChild(optionM);
      }
      if (typeof obj.w !== "undefined") {
        let optionW = document.createElement("option");
        optionW.value = obj.w;
        optionW.text = obj.w;
        select.appendChild(optionW);
      }
      if (typeof obj.d !== "undefined") {
        let optionD = document.createElement("option");
        optionD.value = obj.d;
        optionD.text = obj.d;
        select.appendChild(optionD);
      }
      label.innerHTML = obj.word;
      div.appendChild(label);
      div.appendChild(select);
      break;

    case "list":
      let select2 = document.createElement("select");
      select2.setAttribute("name", obj.word.replace(/ /g, "_"));
      select2.classList.add("w3-select");
      select2.id = obj.word.replace(/ /g, "_");
      select2.setAttribute("id", obj.word.replace(/ /g, "_"));

      for (let listItem = 0; listItem < obj.listCount + 1; listItem++) {
        //console.log(obj[listItem]);
        if (typeof obj[listItem] !== "undefined") {
          let optionL = document.createElement("option");
          optionL.value = obj[listItem];
          optionL.text = obj[listItem];
          select2.appendChild(optionL);
        }
      }
      label.innerHTML = obj.word;
      div.appendChild(label);
      div.appendChild(select2);
      break;

    case "conList":
      let select3 = document.createElement("select");
      select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_"));
      select3.classList.add("w3-select");
      select3.id = obj.word.replace(/ /g, "_");
      let optionDefault = document.createElement("option");
      optionDefault.value = "!none";
      optionDefault.text = "Choose one";
      select3.appendChild(optionDefault);


      for (let listItem = 0; listItem < obj.listCount + 1; listItem++) {
        //console.log(obj[listItem]);
        if (typeof obj[listItem] !== "undefined") {
          let optionL = document.createElement("option");
          let item = obj[listItem];
          optionL.value = item;
          optionL.text = item;
          select3.appendChild(optionL);
          connectedListsArray.push({
            word: item, 
            type: obj["clType-"+item],
            cl: obj.word
          });
        }
      }
      label.innerHTML = obj.word;

      if (obj.listCount == 0) {
        select3 = document.createElement("button");
        select3.setAttribute("value", "!none");
        select3.classList.add("w3-button", "w3-grey", "w3-left-align");
        select3.id = obj.word.replace(/ /g, "_");
        select3.innerHTML = "Show";
        select3.setAttribute("name", "clM-"+obj.word.replace(/ /g, "_"));
        select3.setAttribute("data-word", connectedListsArray[0].word);
      } 

      div.appendChild(label);
      div.appendChild(document.createElement("br"));

      div.appendChild(select3);


      break;

    case "simpleInput":
      let input = document.createElement("input");
      input.setAttribute("type", "text");
      input.setAttribute("name", obj.word.replace(/ /g, "_"));
      input.classList.add("w3-input");
      input.id = obj.word.replace(/ /g, "_");
      label.innerHTML = obj.word;
      div.appendChild(label);
      div.appendChild(input);
      break;
    case "longText":
      let textarea = document.createElement("textarea");
      textarea.setAttribute("name", obj.word.replace(/ /g, "_"));
      textarea.setAttribute("cols", "100");
      textarea.setAttribute("rows", "15");
      textarea.classList.add("w3-input");
      textarea.id = obj.word.replace(/ /g, "_");
      label.innerHTML = obj.word;
      divContainer.classList.remove("w3-half");
      divContainer.classList.add("w3-center");
      div.appendChild(label);
      div.appendChild(textarea);
      break;
    case "current_time":
      let input2 = document.createElement("input");
      let today = new Date();
      let currentTime =
        today.getHours() + ":" + ("0" + today.getMinutes()).slice(-2);
      //console.log(currentTime);
      input2.setAttribute("type", "text");
      input2.setAttribute("name", obj.word.replace(/ /g, "_"));
      input2.setAttribute("value", currentTime);
      input2.id = obj.word.replace(/ /g, "_");
      div.setAttribute("style", "display: none;");
      input2.classList.add("w3-input");
      label.innerHTML = obj.word;
      div.appendChild(label);
      div.appendChild(input2);
      break;
    case "current_date":
      let input3 = document.createElement("input");
      var today2 = new Date();
      var dd = String(today2.getDate()).padStart(2, "0");
      var mm = String(today2.getMonth() + 1).padStart(2, "0"); //January is 0!
      var yyyy = today2.getFullYear();
      currentDate = dd + "." + mm + "." + yyyy;
      input3.setAttribute("type", "text");
      input3.setAttribute("name", obj.word.replace(/ /g, "_"));
      input3.setAttribute("value", currentDate);
      input3.id = obj.word.replace(/ /g, "_");
      div.setAttribute("style", "display: none;");
      input3.classList.add("w3-input");
      label.innerHTML = obj.word;
      div.appendChild(label);
      div.appendChild(input3);
      break;
  }

  //check if item is connected list item cl
  if (obj.cl !== undefined) divContainer.classList.add("hidden");
  if (obj.cl !== undefined) {
    div.lastChild.setAttribute("name",
      (ltPlaceholder !== undefined) ? "cl-"+obj.word.replace(/ /g, "_") +":"+ltPlaceholder : "cl-"+obj.word.replace(/ /g, "_"));
  }

  //append field to wrapper and add to mainForm
  divContainer.appendChild(div);
  form.appendChild(divContainer);

  buildSidebarList(obj, sidebarList) 

  //handle conList items 
  if (obj.type == "conList") {
    //build connected list fields according to obj
    for (let conObj of connectedListsArray) {
      buildField(conObj, form, sidebarList);
    }

    //set formEvent for selection detection to mainForm
    if (obj.listCount == 0) {
      document.getElementById("mainForm").addEventListener("click", (e) => {
        if (e.target && e.target.matches("button#"+obj.word.replace(/ /g, "_"))) {
          let button = document.getElementById(obj.word.replace(/ /g, "_"));
          let con = button.dataset.word;
          let conElement = document.getElementById(con);
        if (conElement.parentElement.parentElement.classList.contains("hidden")) {
            conElement.parentElement.parentElement.classList.remove("hidden");
            button.value = "!selected";
          } else {
            conElement.parentElement.parentElement.classList.add("hidden");
            button.value = "!none";
          }
        }
      });
    } else {
      document.getElementById("mainForm").addEventListener("change", (e) => {
        if (e.target && e.target.matches("select#"+obj.word.replace(/ /g, "_"))) {
          let select = document.getElementById(obj.word.replace(/ /g, "_"));
          for (let opt of select.options) {
            if (opt.value == "!none") continue;
            if (opt.innerHTML != select.value) {
              document.getElementById(opt.innerHTML.replace(/ /g, "_")).parentElement.parentElement.classList.add("hidden");
            } else {
              document.getElementById(select.value.replace(/ /g, "_")).parentElement.parentElement.classList.remove("hidden");
            }
          }
          for (let hiddenItems of document.getElementsByClassName("cl")) {
            if (hiddenItems.innerHTML != select.value) {
              hiddenItems.classList.add("hidden");
            } else {
              hiddenItems.classList.remove("hidden");
            }
          }
        }
      });
    }
  }
}

function buildSidebarList(obj, sidebarList) {
      //build sidebarlist item and append
      let sidebarListItem = document.createElement("li");
      sidebarListItem.classList.add(
        "w3-bar-item",
        "w3-padding-large",
        "w3-button",
        "sb-item"
      );
      if (obj.cl !== undefined) sidebarListItem.classList.add("hidden", "cl");
      sidebarListItem.style.borderBottom = "1px solid #ddd";
      sidebarListItem.id = "sb-item";
      sidebarListItem.setAttribute("data-item", obj.word.replace(/ /g, "_"));
      sidebarListItem.innerHTML = obj.word;
      sidebarListItem;
      sidebarList.appendChild(sidebarListItem);
}

function userFileNameDiv(fileName) {
  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");
  div.setAttribute("style", "padding: 5px");
  let userFileNameInput = document.createElement("input");
  userFileNameInput.setAttribute("type", "text");
  userFileNameInput.setAttribute("name", "userFileName");
  userFileNameInput.setAttribute("placeholder", fileName);
  userFileNameInput.classList.add("w3-input");
  userFileNameInput.id = "userFileName";
  div.appendChild(userFileNameInput);
  divContainer.appendChild(div);
  return divContainer;
}

export default transformTemplateObject;
