import sha256 from "./sha256.min.js";
import XORCipher from "./xorc.js";
import getBrowserFingerprint from "./identify.js"
import { loadNavBar } from "./web.js";

export const passwordHash = {
  toString: () => {
    let fp = getBrowserFingerprint( { hardwareOnly: true } );
    let data;
    try {
      data = window.sessionStorage.getItem(sha256(fp));
    } catch (e) {
      return "none";
    }
    if (data === null) return "none";
    return XORCipher.decode(fp, data);
  },

  set: (pw) => {
    let fp = getBrowserFingerprint( { hardwareOnly: true } );
    window.sessionStorage.setItem(sha256(fp), XORCipher.encode(fp, pw));
  }
}



function setPassword() {
  let x = document.getElementById("loginForm");
  let pw = x.elements[0].value;
  let cookieFlag = x.elements[1].value;

  if (pw != "" || pw !== "undefined") {
    let pwOld = pw;
    passwordHash.set(sha256(pw));
    let data = window.localStorage.getItem(sha256('chk'));
    if (data !== null) {
      let chk = XORCipher.decode(passwordHash.toString(), data);
      if (chk != "") {
        try {
          JSON.parse(chk);
        } catch (e) {
          document.getElementById("wrongPWAlert").style.display = "block";
          const alertTimeout = setTimeout(() => {
            document.getElementById("wrongPWAlert").style.display = "none";
          }, 5000);
          passwordHash.set(pwOld);
          x.elements[0].value = "";
          return;
        }
      }
    }

    //user logged in
    //load NavigationBar with templates according to server

    //set cookie if flag is true
    loadNavBar();
    document.getElementById("login").style.display = "none";
    window.sessionStorage.setItem(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash.toString()));
    if (cookieFlag == 'on') {
      setCookie(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash.toString()), 30)
    }
  }
}

export function getUsrId() {
  const fingerprint = getBrowserFingerprint( { hardwareOnly: true } );
  return cyrb53(fingerprint + passwordHash);
}

const cyrb53 = (str, seed = 21) => {
  let h1 = 0xdeadbeef ^ seed,
    h2 = 0x41c6ce57 ^ seed;
  for (let i = 0, ch; i < str.length; i++) {
    ch = str.charCodeAt(i);
    h1 = Math.imul(h1 ^ ch, 2654435761);
    h2 = Math.imul(h2 ^ ch, 1597334677);
  }
  
  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
  
  return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

export function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return null;
}


export default setPassword;
