import { retrieveData } from "./storage.js";
import sha256 from "./sha256.min.js";
import XORCipher from "./xorc.js";
import getBrowserFingerprint from "./identify.js"


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

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

  if (pw != "" || pw !== "undefined") {
    let pwOld = pw;
    passwordHash.set(sha256(pw));
    let templateFiles = retrieveData("templateFiles");
    if (templateFiles != "") {
      try {
        JSON.parse(templateFiles);
      } 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

    document.getElementById("login").style.display = "none";
    window.sessionStorage.setItem(sha256("verified"), XORCipher.encode(sha256("passwordHash"), passwordHash));
  }
}

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

export default setPassword;
