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

export const passwordHash = {
  name: cyrb53("m21_"+getBrowserFingerprint( { hardwareOnly: true } )),
  toString: function () {
    let token = window.activeState.sessionToken;
    if (token == null) return "";
    if (token == "") return "";
    return XORCipher.decode(this.name, token);
  },
  set: function (pw) {
    if (pw == "") return;
    activeState.sessionToken = XORCipher.encode(this.name, pw);
  },
  initHash: function () {
    //check if cookie exists
    if (getCookie(sha256(this.name)) != null) {
      if (getCookie(sha256(this.name)) != "") {
        this.set(XORCipher.decode(sha256(this.name), getCookie(sha256(this.name))));
      }
    }
    let verifiedStatus = false;
    let tF = retrieveData("templateFiles");
    if (tF != null) {verifiedStatus = true}


    if (verifiedStatus == true) {
      //set user id
      activeState.userId = getUsrId();
      setCookie(sha256(this.name), XORCipher.encode(sha256(this.name), this), 10);
    }
  },
  verify: function () {
    if (passwordHash == "") return false;
    let verifiedStatus = false;
    let tF = retrieveData("templateFiles");
    if (tF != null) verifiedStatus = true
    return verifiedStatus;
  }
}

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

  if (pw != "" || pw !== "undefined") {
    passwordHash.set(sha256(pw));
    let tF = retrieveData("templateFiles");
    if (tF == null) {
      wrongPwAlert();
      passwordHash.set("");
      x.elements[0].value = "";
      return;
    }
    //user logged in

    //make sure to bring back persistent stat after logout
    activeState.settings.persistentStorage = "true";
    tF = retrieveData("templateFiles");
    if (tF == null || tF.length == 0) {
      activeState.settings.persistentStorage = "false";
    }

    document.getElementById("login").style.display = "none";
    setCookie(sha256(passwordHash.name), XORCipher.encode(sha256(passwordHash.name), passwordHash), 10)
  }
}

function wrongPwAlert() {
  let wrongPWAlert = document.getElementById("wrongPWAlert");
  wrongPWAlert.style.display = "block";
  wrongPWAlert.addEventListener("click", (e) => {
    if (e.target && e.target.tagName === "A") {
      clearStorage();
      document.getElementById("wrongPWAlert").innerHTML = 
        "<p>all files cleared - set new password</p>";
    }
  });
}

function 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 getUsrId() {
  const fingerprint = getBrowserFingerprint( { hardwareOnly: true } );
  return cyrb53(fingerprint + passwordHash);
}

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=/";
}

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 function logout() {
  let id = sha256(passwordHash.name);
  activeState.sessionToken = "";
  setCookie(sha256(passwordHash.name), "", 10);
  document.cookie = id + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  document.getElementById("passwordField").value = "";
  document.getElementById("login").style.display = "block"; 
}



export function sanitize(string) {
  const map = {
      '&': '_',
      '<': '_',
      '>': '_',
      '"': '_',
      "'": '_',
      '/': '_',
      '`': '_',
      '=': '_'
  };
  const reg = /[&<>"'/]/ig;
  return string.replace(reg, (match)=>(map[match]));
}

export function isAlphaNumeric(str) {
  var code, i, len;

  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);
    if (!(code > 47 && code < 58) && // numeric (0-9)
        !(code > 64 && code < 91) && // upper alpha (A-Z)
        !(code > 96 && code < 123)) { // lower alpha (a-z)
      return false;
    }
  }
  return true;
};

export const inputRead = {
  init: function () {
    this.event = "";
    this.inputString = "";
    this.source = "";
    this.inputContent = "";
    this.lastRunTime = new Date();
    this.target = document.getElementById("toggleFilesMenu");
    this.lastExecId = "";
  },
  read: function (event) {
    this.event = event;
    this.source = event.srcElement.id;
    let previousContent = this.inputContent;
    let key = (event.key !=undefined) ? event.key : "";
    let contentElement = document.getElementById(this.source);
    this.inputContent = (contentElement != undefined) ? contentElement.value + key : "";

    if (this.inputContent == "" || key == "") return;
    if (key.length > 1) return;
    if (event.ctrlKey) return;
    if (this.inputContent == previousContent) return;

    this.lastRunTime = new Date();
    clearTimeout(this.lastExecId);

    this.target.style.borderBottom = "3px solid #c0392b";
    this.target.innerHTML = "";
    let i = document.createElement("i");
    i.classList.add("fa", "fa-save");
    this.target.appendChild(i);
    this.lastExecId = setTimeout(() => {
      createStorageObj();
      this.target.style.borderBottom = "none";
      this.target.innerHTML = "";
      let i = document.createElement("i");
      i.classList.add("fa", "fa-file");
      this.target.appendChild(i);
    }, 1000);
  },
}

export function getCurrentDate() {
  let date = new Date();
  let uts = Date.now();
  let current_hour = date.getHours();
  current_hour = current_hour <= 9 ? "0" + current_hour : current_hour;
  let current_minute = date.getMinutes();
  current_minute = current_minute <= 9 ? "0" + current_minute : current_minute;
  let current_second = date.getSeconds();
  current_second = current_second <= 9 ? "0" + current_second : current_second;
  let current_month = date.getMonth() + 1;
  current_month = current_month <= 9 ? "0" + current_month : current_month;
  let current_day = date.getDate();
  current_day = current_day <= 9 ? "0" + current_day : current_day;
  let current_year = date.getFullYear();
  

  let current_time = current_hour + ":" + current_minute;
  let current_time_long = current_hour + ":" + current_minute + ":" + current_second;
  let current_date = current_day + "." + current_month;
  return {
    current_time: current_time,
    current_time_long: current_time_long,
    current_date: current_date,
    current_year: current_year,
    uts: uts
  };
}

export default setPassword;
