from ploneintranet import api as pi_api
from ploneintranet.notifications.browser.interfaces import (
    IPloneintranetNotificationsLayer,
)
from ploneintranet.notifications.sql import saconfig
from zope.globalrequest import getRequest

import logging

logger = logging.getLogger(__name__)


def notification_events_enabled():
    if not IPloneintranetNotificationsLayer.providedBy(getRequest()):
        # We are not installed
        return False

    event_key = "ploneintranet.notifications"
    enabled = pi_api.env.is_enabled(event_key)  # default is enabled
    if not enabled:
        logger.debug("%s disabled", event_key)
    return enabled


def newsitem_statechanged(obj, event):
    """Log an event related to review state change events.

    Currently only bound to INewsItem. If you want to generalize this,
    either generalize this fuction for Products.CMFCore.interfaces.IContentish,
    or provide separate handlers per portal type.
    """
    if not notification_events_enabled():
        return

    if event.new_state.id not in {"published"}:
        # Retracted: cancel future notifications
        saconfig.delete_unprocessed_events_for(obj, "newsitem_published")
    elif saconfig.get_events_for(obj, "newsitem_published").count() == 0:
        # Published: only log an event if it's not there yet
        saconfig.log_event(obj, "newsitem_published")


def newsitem_removed(obj, event):
    """Remove any pending logged_event for a future news item."""
    if not notification_events_enabled():
        return

    # For any already-processed events, we rely on the context check throwing a
    # MissingContextError
    saconfig.delete_unprocessed_events_for(obj, "newsitem_published")
