import { hideMenus, showMenu, logout } from "./evts.js";
import setPassword, { passwordHash } from "./scripts.js";
import { getUsrId, getCookie } from "./scripts.js";
import XORCipher from "./xorc.js";
import sha256 from "./sha256.min.js";
import { loadNavBar } from "./web.js";


window.activeState = {
  userId: getUsrId(),
  articles: '',
  currentPage: 1
};


function init() {

  let pw = '4d4e872ebd8886fd374d09c82ef88be1a792dfd21c5a017db4c34d55b2fbb7b3';
  window.localStorage.setItem(sha256("chk"), XORCipher.encode(pw, JSON.stringify({verified: pw})));
  //check if user is logged in 
  let verfiedStatus = window.sessionStorage.getItem(sha256("verified"));
  if (verfiedStatus == '') {verfiedStatus = null}
  if (verfiedStatus != null) {
    //user logged in

    //write verifiedStatus content into passwordHash for decode check later
    passwordHash.set(XORCipher.decode(sha256("passwordHash"), verfiedStatus));
    document.getElementById("login").style.display = "none";
    //load NavigationBar with templates according to server
    loadNavBar();
  } else {
    //check if cookie exists
    if (getCookie(sha256("verified")) != null) {
      passwordHash.set(XORCipher.decode(sha256("passwordHash"), getCookie(sha256("verified"))));
      document.getElementById("login").style.display = "none";
      //load NavigationBar with templates according to server
      loadNavBar();
    } else {
      document.getElementById("login").style.display = "block";
    }
  }



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

  //print current version to footer
  printVersion();

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


  
}

function eventListeners() {

//add hideMenu to Body
document
  .getElementsByClassName("w3-main")[0]
  .addEventListener("click", hideMenus);

//add set Password to loginForm
document
  .getElementById("submitPassword")
  .addEventListener("click", setPassword);

//add toggle Navigation Menu
document
  .getElementById("toggleNavigationMenu")
  .addEventListener("click", showMenu);

//add sign out
document
  .getElementById("logout")
  .addEventListener("click", logout);

}

function printVersion() {
  const scripts = document.getElementsByTagName("script");
  const versionSpan = document.getElementById("currentVersion").lastChild;

  for (var i=0;i<scripts.length;i++) {
    if (scripts[i].src) {
      let source = scripts[i].src;
      // js/version/main.js
      let pathVersion = source.split("/");
      pathVersion = pathVersion[pathVersion.length-2];
      //add it to document footer currentVersion
      versionSpan.textContent = "version: " + pathVersion;
    }
 }
}

export default init;
