from plone import api
from plone.base.interfaces.siteroot import IPloneSiteRoot
from ploneintranet.notifications.interfaces import IProvideContextUID
from ploneintranet.notifications.interfaces import IResolveContextUID
from zope.component import adapter
from zope.interface import implementer
from zope.interface import Interface
from zope.interface import provider


@adapter(Interface)
@implementer(IProvideContextUID)
def default_event_context_uid_provider(context):
    """Default adapter that converts the context to a UID
    that will be stored in the notification table.
    """
    return f"UID:{context.UID()}"


@provider(IResolveContextUID)
def default_event_context_uid_resolver(uid):
    """Default utility that converts the UID stored in the notification table
    in to an object.
    """
    return api.content.get(UID=uid)


@adapter(IPloneSiteRoot)
@implementer(IProvideContextUID)
def plonesite_event_context_uid_provider(context):
    """This adapter makes no sense in Plone 6 because the Plone portal has a UID.
    We return the path to make it work in Plone 5.
    """
    path = "/".join(context.getPhysicalPath())
    return f"PloneSite:{path}"


@provider(IResolveContextUID)
def plonesite_event_context_uid_resolver(uid):
    """Get the site from the uid (which is expected to be a path)"""
    return api.portal.get().restrictedTraverse(uid)
