import {
  hideMenus,
  showMenu,
  showSidebar,
  showTextBlocks,
  clickImportFiles,
  modalNotifier,
  printVersion,
  copyToClipBoard
} from "./evts.js";
import { buildFile } from "./files.js";
import setPassword, {
  passwordHash,
  inputRead
} from "./scripts.js";
import parseForm from "./parseForm.js";
import { createStorageObj, storeSettings } from "./storage.js";
import { loadNavBar, initTextBlocks, loadNewTemplate } from "./web.js";

window.activeState = {
  userId: "",
  sessionToken: "",
  activePage: "landing",
  loadedTemplate: "",
  fileName: "",
  lastElement: "",
  serverFilesTs: "",
  settings: {
    localOnly: "true",
    lineBreak: 120,
    font: "Arial",
    fontSize: "10px",
    notifierPause: 1,
    persistentStorage: "false",
    enablePell: "false",
    debug: "false"
  },
  templates: [],
  templateObjectsPurified: [],
  templateObjects: [],
  fullString: "",
  templateFieldTypes: [
    "simpleInput",
    "longText",
    "hiddenField",
    "current_time",
    "current_date",
    "markup",
    "title",
  ],
  markups: ["title", "link", "italic", "green_highlighted", "highlighted"],
  storage: [],
  orgPage: {
    main: {},
    sidebar: {}
  }
};

function init() {

  //init passwordhash to retrieve cookie info and set passwordHash
  passwordHash.initHash();

  //check if user is logged in
  if (passwordHash.verify()) {
    //user logged in
    document.getElementById("login").style.display = "none";
  } else {
    document.getElementById("login").style.display = "block";
  }

  //load settings from storage and apply
  let settings = storeSettings("getInit", true);
  if (settings != null) {
    for (let setting of Object.entries(settings)) {
      activeState.settings[setting[0]] = setting[1];
    } 
  }

  //load NavigationBar with templates according to server
  loadNavBar();

  //init Textblocks field with entries according to server
  initTextBlocks();

  //add event listeners to document and window
  eventListeners();

  //print current version and storage mode to footer
  let msg = (activeState.settings.persistentStorage == "false") ? "temporary" : "persistent";
  printVersion("storage mode: "+msg+" |");

  //adjust title for mobile use
  if (screen.width < 993) {
    document.getElementById("siteTitle").innerHTML = "TG";
  }

  //backup landing page
  activeState.orgPage.sidebar = document.getElementById("sidebar");

  activeState.orgPage.main = document.getElementById("mainForm");
}

function eventListeners() {
  //add hideMenu to Body
  document
    .body
    .addEventListener("click", (e) => hideMenus(e));

  //add set Password to loginForm
  document
    .getElementById("submitPassword")
    .addEventListener("click", setPassword);
  //add toggle Navigation Menu
  document
    .getElementById("toggleNavigationMenu")
    .addEventListener("click", showMenu);
  //add loadTemplateBtn event showMenu
/*   document
    .getElementById("loadTemplateBtn")
    .addEventListener("click", showMenu); */
  //add toggle sideBar Menu
  document
    .getElementById("toggleSidebarMenu")
    .addEventListener("click", showSidebar);
  //add toggle files Menu and sidebar button
  document
    .getElementById("toggleFilesMenuSB")
    .addEventListener("click", buildFile);
  document
    .getElementById("toggleFilesMenu")
    .addEventListener("click", buildFile);

  //add toggle textBLocks Menu
  document
    .getElementById("toggleTestBlocksMenu")
    .addEventListener("click", showTextBlocks);

  //add saveFiles to server listener on launch page
  document
    .getElementById("importFilesSB")
    .addEventListener("click", () => clickImportFiles());

  //add key listener for ctrl s in form mode
  inputRead.init();
  window.addEventListener("keydown", (e) => {
    if (activeState.activePage == "template") {
      inputRead.read(e);
      if (e.ctrlKey && e.key == "s") {
        createStorageObj("copy");
        copyToClipBoard(parseForm());
        modalNotifier("File copied to clipboard", activeState.settings.notifierPause);
        let copyButton = document.getElementById("fromCopyBtn");
        copyButton.className = "w3-button w3-flat-carrot";
        copyButton.value = "Copied";
        e.preventDefault();
      }
    }
  });

  //add url listener
  window.addEventListener("hashchange", (e) => {
    
    let newURLArr = e.newURL.split("/");
    let template;
    if (newURLArr != undefined) {
      template = newURLArr[newURLArr.length -1];
      if (template != undefined) {
        template = template.split("=")[1];
        if (template != undefined) {
          if (activeState.templates.includes("")) {
            loadNewTemplate(template);
          }
        }
      }
    }
  });
}

init();
