//class Form {
//    constructor () {
//       this.buildForm = buildForm;
//       this.retrieveForm = retrieveForm;
//   }
//
//
//
//}

import { storeData, createStorageObj } from "./storage.js";
import parseInput from "./parseTemplate.js";
import transformTemplateObject from "./buildForm.js";
import { showSidebar, handleOnBlur } from "./evts.js";
import parseFormOnSubmit, { parseTextMarkups } from "./parseForm.js";

function buildForm(templateInput, loadOnly = false) {
  var wordArray = [];

  //display set Form button
  document.getElementById("setFormButton").style.display = "block";

  //check for presets in "-form.txt" file; indicated by !JSON_placeholder
  if (templateInput.indexOf("!JSON_placeholder:") !== -1) {
    let jsonPlaceholder = templateInput.split("!JSON_placeholder:")[1];
    templateInput = templateInput.split("!JSON_placeholder:")[0];
    storeData("templatePreset", jsonPlaceholder);
  }
  //start building wordArray by splitting input by line win/unix and define eol char for recreating templateInput
  let eol;
  if (templateInput.indexOf("\r\n") !== -1) {
    eol = false;
    var wordArrayByLine = templateInput.split("\r\n");
  } else {
    eol = true;
    var wordArrayByLine = templateInput.split("\n");
  }
  //finish building wordArray by Looping through lines and spliting it into one array of words
  //also create temporary templateInput to exclude comments
  let templateInputArr = [];
  for (let wordArrayByLineLine of wordArrayByLine) {
    //ignore "#" comment lines
    if (wordArrayByLineLine.substring(0, 1) == "#") {
      continue;
    }

    //add words ob lines to wordArray
    wordArray = wordArray.concat(wordArrayByLineLine.split(" "));
    //add line to temp templatearray
    templateInputArr.push(wordArrayByLineLine);
  }

  //create templateInput without comments
  templateInput = templateInputArr.join(eol ? "\n" : "\r\n");

  //parse text markups like !l !n in templateInput
  templateInput = parseTextMarkups(templateInput);

  //set objects array for parseInput Function
  var objects = [];
  //loop through words, parse it individually and add it to objects array


  for (let i = 0; i < wordArray.length; i++) {
    parseInput(wordArray, objects, i);
    //console.log(wordArray[i]);
  }

  //set individual positionens of objects in string and add it to objects
  setStringPos(objects, templateInput);

  //save objects array and template file string for web.js in session storage
  window.sessionStorage.setItem("templateObjects", JSON.stringify(objects));
  window.sessionStorage.setItem("fullString", templateInput);

  //sort objects array by words prio
  objects = prioritizeArray(objects);

  //remove non display objects and safe it to session storage
  let objectsPurified = purifyObjects(objects);
  window.sessionStorage.setItem(
    "templateObjectsPurified",
    JSON.stringify(objectsPurified)
  );

  //reset page and event listeners
  let mainFormDiv = document.getElementById("mainForm");
  let outputDiv = document.getElementById("output");
  let submitContainerDiv = document.getElementById("submitContainer");
  let sidebarDiv = document.getElementById("sidebar");
  //sidebarDiv.replaceWith(sidebarDiv.cloneNode(true));

  mainFormDiv.innerHTML = "";
  mainFormDiv.replaceWith(mainFormDiv.cloneNode(true));
  outputDiv.innerHTML = "";
  outputDiv.replaceWith(outputDiv.cloneNode(true));
  submitContainerDiv.innerHTML = "";
  submitContainerDiv.replaceWith(submitContainerDiv.cloneNode(true));
  sidebarDiv.innerHTML = "";

  //finally build html code for Form and siddebar and add it to dom if needed
  if (loadOnly) {return};
  
  transformTemplateObject(objectsPurified);
  //add events
  formEvts();
}

function prioritizeArray(objects) {
  let prioArray = [];
  let objects_sorted = [];

  for (let valPreSorted of objects) {
    prioArray.push(valPreSorted.prio);
  }
  prioArray.sort(function (a, b) {
    return a - b;
  });
  //console.log(prioArray);
  for (let valSorted of prioArray) {
    for (let obj of objects) {
      if (valSorted === obj.prio) {
        objects_sorted.push(obj);
        if (obj.prio !== 0) {
          break;
        }
      }
    }
  }
  return objects_sorted;
}

function purifyObjects(objects) {
  let objectsPurified = [];
  let objectsPrePurified = [];
  for (let objPrePurified of objects) {
    if (!objectsPrePurified.includes(objPrePurified.word)) {
      objectsPurified.push(objPrePurified);
    }
    objectsPrePurified.push(objPrePurified.word);
  }
  return objectsPurified;
}

function setStringPos(objects, fullStringMaster) {
  let stringCursor = 0;
  let startPos = 0;
  let endPos = 0;
  let fullString = "";
  for (let obj of objects) {
    fullString = fullStringMaster.substring(stringCursor);
    if (fullString.indexOf("%" + obj.word) !== -1) {
      startPos = 0;
      endPos = 0;
      startPos = fullString.indexOf("%" + obj.word) + stringCursor;
      let objPrioLength = 1;
      if (obj.prio > 9) {
        objPrioLength = 2;
      }
      if (obj.prio == 0) {
        objPrioLength = 0;
      }

      switch (obj.type) {
        case "simpleInput":
          endPos = startPos + 2 + obj.word.length + objPrioLength;
          break;
        case "genderSpecific":
          let gSC = 0;
          if (typeof obj.m !== "undefined") {
            gSC = gSC + obj.m.length + 3;
          }
          if (typeof obj.w !== "undefined") {
            gSC = gSC + obj.w.length + 3;
          }
          if (typeof obj.d !== "undefined") {
            gSC = gSC + obj.d.length + 3;
          }
          endPos = startPos + 2 + gSC + objPrioLength + obj.word.length + 1;
          break;
        case "list":
          let gSC1 = 0;
          for (
            let objListItem = 0;
            objListItem < obj.listCount + 1;
            objListItem++
          ) {
            if (typeof obj[objListItem] !== "undefined") {
              gSC1 = gSC1 + obj[objListItem].length + 3;
            }
          }
          endPos = startPos + 2 + gSC1 + objPrioLength + obj.word.length + 1;
          break;
        case "conList":
          let gSC2 = 0;
          for (
            let objListItem = 0;
            objListItem < obj.listCount + 1;
            objListItem++
          ) {
            if (typeof obj[objListItem] !== "undefined") {
              gSC2 = gSC2 + obj[objListItem].length + obj["clType-"+obj[objListItem]].length + 4;
              if (obj["clType-"+obj[objListItem]] == "cl-simpleInput") {
                gSC2 = gSC2 - obj["clType-"+obj[objListItem]].length;
              }
            }
          }
          endPos = startPos + 2 + gSC2 + objPrioLength + obj.word.length + 1;
          break;
        default:
          endPos =
            startPos +
            2 +
            obj.word.length +
            1 +
            obj.type.length +
            objPrioLength;
          break;
      }
      obj.spos = startPos;
      obj.epos = endPos;
      stringCursor = endPos;
    }
  }
}

function formEvts() {
  //add event for main copy button
  document.getElementById("submitContainer").addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "INPUT") {
      switch (e.target.value) {
        case "Copy":
          createStorageObj();
          parseFormOnSubmit();
          e.target.className = e.target.className.replace(" w3-grey", " w3-flat-carrot");
          e.target.style.pointerEvents = "none";
          const timeoutCopy = setTimeout(() => {
            e.target.className = e.target.className.replace(" w3-flat-carrot"," w3-grey");
            e.target.style.pointerEvents = "auto";
          }, 250);
          break;
        case "Save":
          createStorageObj();
          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);
          break;
        default:
          e.preventDefault;
      }
    }
  });

  //add sidebar events
  document.getElementById("sidebar").addEventListener("click", (e) => {
    if (e.target) {
      if (e.target.id == "sb-submit") {
        if (screen.width < 993) {
          showSidebar();
        }
        parseFormOnSubmit();
        focusOnField("output");
      }
      if (e.target.id == "sb-item") {
        setTimeout(() => {
          focusOnField(e.target.dataset.item);
        }, 100);
      }
    }
  });

  //add handle on blur event listener
  document.getElementById("mainForm").addEventListener("click", (e) => {
    if (e.target && e.target.matches("div.w3-section")) {
      e.preventDefault;
      handleOnBlur(e.target);
    }
  });
}

function focusOnField(id) {
  let targetElement = document.getElementById(id);
  if (targetElement == null) return;
  
  document.activeElement.blur();
  targetElement.focus();
  setTimeout(function () {
    let offset = targetElement.offsetTop - 100;
    window.scrollTo(0, offset);
  }, 100);
}

export default buildForm;
