const cryptoProvider = window["CryptoJS"];
const cryptoAlgorithm = window["CryptoJS"].AES;
const _secretKey = "unibase";
export function encrypt(content) {
  return cryptoAlgorithm.encrypt(content, _secretKey).toString();
}

export function decrypt(encoded) {
  return cryptoAlgorithm
    .decrypt(encoded, _secretKey)
    .toString(cryptoProvider.enc.Utf8);
}

export function setCookie(cname, cvalue, exdays) {
  let _cookievalue = "";
  if (cvalue) {
    _cookievalue = encrypt(cvalue);
  }
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = "expires=" + d.toUTCString();
  document.cookie =
    cname +
    "=" +
    _cookievalue +
    ";" +
    expires +
    ";path=/;samesite=none;secure=true";
}

export function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) === " ") {
      c = c.substring(1);
    }

    if (c.indexOf(name) === 0) {
      var cookie = c.substring(name.length, c.length);
      var cookie_decrypt = decrypt(cookie);
      return cookie_decrypt;
    }
  }
  return "";
}

export function isAuthenticated() {
  if (getCookie("_idty")) {
    return true;
  }
  return false;
}
