from BTrees.OOBTree import OOTreeSet
from logging import getLogger
from plone import api
from plone.memoize.view import memoize
from plone.memoize.view import memoize_contextless
from ploneintranet.core import _
from ploneintranet.layout.browser.base import BaseView
from ploneintranet.layout.interfaces import IDiazoNoTemplate
from zope.annotation import IAnnotations
from zope.interface import implementer

logger = getLogger(__name__)


@implementer(IDiazoNoTemplate)
class LinkView(BaseView):
    """"""

    cart_key = "ploneintranet.library.cart"

    def maybe_disable_diazo(self):
        return False

    @property
    @memoize_contextless
    def library_url(self):
        portal = api.portal.get()
        library = portal.get("library")
        return library and library.absolute_url() or ""

    @property
    @memoize_contextless
    def available(self):
        """Check if this button should be rendered"""
        return api.portal.get_registry_record(
            "ploneintranet.library.enable_pdf_download_ui", default=False
        )

    def action(self):
        """The action for this view"""
        return "remove" if self.is_active() else "add"

    def action_class(self):
        """The css class for this button"""
        return "active" if self.is_active() else ""

    def action_title(self):
        """The title for this action"""
        if self.is_active():
            return _("Remove this libary item from your download list")
        else:
            return _("Add this library item to your download list")

    @memoize
    def is_active(self):
        """Check if this document is active"""
        annotations = IAnnotations(self.user, {})
        if self.cart_key not in annotations:
            # Not yet initialized or not a userprofile
            return False
        return self.context.UID() in annotations[self.cart_key]

    def add(self):
        """Add this item to the annotations"""
        annotations = IAnnotations(self.user, None)
        if annotations is None:
            return
        if self.cart_key not in annotations:
            annotations[self.cart_key] = OOTreeSet()
        annotations[self.cart_key].add(self.context.UID())

    def remove(self):
        """Remove this item from the annotations"""
        storage = IAnnotations(self.user, {}).get(self.cart_key)
        storage.remove(self.context.UID())

    def maybe_toggle(self):
        """Check if we should toggle the selected state for this document
        and this user
        """
        action = self.request.get("action")
        if not action:
            return
        is_active = self.is_active()
        if action == "remove" and is_active:
            self.remove()
        elif action == "add" and not is_active:
            self.add()
        self.purge_memoize()

    def __call__(self):
        self.maybe_toggle()
        return super().__call__()
