from hashlib import sha1
from plone import api
from plone.app.layout.viewlets.common import ViewletBase
from plone.memoize import ram
from plone.memoize.view import memoize_contextless
from ploneintranet import api as pi_api
from ploneintranet.layout.browser.proto import _forever_cache_key


class Headers(ViewletBase):
    # XXX is this used at all?
    notification_filter = ""

    @property
    def url(self):
        return api.portal.get_registry_record(
            "ploneintranet.layout.push_server_reader_url", default=""
        )

    @property
    def login(self):
        if self.token:
            # Which is the userid
            return self.filter
        return api.portal.get_registry_record(
            "ploneintranet.layout.push_server_reader_login", default=""
        )

    @property
    def token(self):
        return api.portal.get_registry_record(
            "ploneintranet.layout.push_token", default=""
        )

    @ram.cache(_forever_cache_key)
    def password_for_username(self, username: str, token: str) -> str:
        """Simple token based authentication for a user"""
        return sha1(f"{username}:{token}".encode()).hexdigest()

    @property
    def password(self):
        if self.token:
            # Which is the userid
            return self.password_for_username(self.filter, self.token)
        return api.portal.get_registry_record(
            "ploneintranet.layout.push_server_reader_password", default=""
        )

    @property
    def exchange(self):
        return api.portal.get_registry_record(
            "ploneintranet.layout.push_exchange", default=""
        )

    @property
    def notification_exchange(self):
        return api.portal.get_registry_record(
            "ploneintranet.layout.notification_exchange", default=""
        )

    @property
    @memoize_contextless
    def filter(self):
        user = pi_api.userprofile.get_current()
        if not user:
            return ""
        return user.getId()

    def available(self):
        """This viewlet should be available when it makes sense, i.e.:
        - we have a user
        - push is properly configured
        """
        if api.user.is_anonymous():
            return False
        if not (self.url and self.exchange):
            return False
        return True
