import hashlib
from django.conf import settings
from ocyan.main.loading import get_ocyan_classes

# pylint: disable=unbalanced-tuple-unpacking
CookieContext, NoCookiesContext = get_ocyan_classes(
    "cookie_jar.context", ["CookieContext", "NoCookiesContext"]
)


def public_user_id(user):
    salt_str = "public_user_id %s" % settings.SECRET_KEY
    salt = hashlib.sha256(salt_str.encode()).hexdigest()
    str_to_hash = "%s%s%s%s%s%s" % (
        user.id,
        user.date_joined,
        user.last_name,
        user.first_name,
        user.email.replace("@", "->"),
        salt,
    )
    return hashlib.sha256(str_to_hash.encode()).hexdigest()


def cookie_jar(request):
    if "profile-script-impact" in request.GET:
        return {"cookie_jar": NoCookiesContext(request)}

    context = {"cookie_jar": CookieContext(request)}

    if request.user.is_authenticated:
        context["public_user_id"] = public_user_id(request.user)

    return context
