from plone import api
from ploneintranet.asynctasks.celeryconfig import ASYNC_ENABLED
from ploneintranet.asynctasks.tasks import ReindexObjectedSecurityForShared
from zope.globalrequest import getRequest

import logging

log = logging.getLogger(__name__)


def central_calendar_deleted(obj, event):
    catalog = api.portal.get_tool(name="portal_catalog")
    uid = api.content.get_uuid(obj=obj)
    brains = catalog(shared_calendar=uid)
    for brain in brains:
        obj = brain.getObject()
        obj.shared_calendar = None
        api.content.transition(obj=obj, to_state="published")


def central_calendar_modified(obj, event):
    """Reindex events' security indexes to reflect changed calendar
    setting.
    """
    if ASYNC_ENABLED:
        ReindexObjectedSecurityForShared(obj)()
    else:
        view = api.content.get_view(
            ReindexObjectedSecurityForShared.url.lstrip("@"), obj, getRequest()
        )
        view()
