from plone import api
from ploneintranet.core import _
from ploneintranet.notifications.sql import saconfig


def _message_submitting_user(obj):
    # If the event was submitted to a calendar without auto-accept, give feedback
    # to the user to inform them that they need to have patience.
    if api.content.get_state(obj) == "central_calendar":
        return
    message = _(
        "calendar_feedback_submitted_user",
        default="Shares on this calendar need to be accepted by one of "
        "its maintainers before they become visible. You will receive a "
        "notification once the event is accepted by one of the maintainers "
        "of this calendar.",
    )
    api.portal.show_message(message, request=obj.REQUEST, type="info")


def update_event_workflow(obj, event):
    """When an event is added/removed to a shared calendar,
    we need to trigger a workflow state change.
    Depending on the user permissions and on the calendar settings,
    the event might need to be approved by a calendar maintainer.
    """
    # We are only interested in modifications that affect the shared_calendar field
    if not any(["shared_calendar" in desc.attributes for desc in event.descriptions]):
        return

    # if the event was previously submitted/accepted into another calendar,
    # withdraw from there and remove all stale old review notifications
    if api.content.get_state(obj=obj) != "published":
        # We cannot use to_state="published" here because
        # the retract and reject transitions both go from the same
        # starting state to the same end state - and plone.api
        # doesn't handle that scenario properly.
        api.content.transition(obj=obj, transition="retract")

    # now submit the event to the newly assigned calendar
    if obj.shared_calendar:
        api.content.transition(
            obj=obj,
            # can't use to_state='pending' because of the automatic
            # transition
            transition="submit",
        )
        saconfig.log_event(
            obj,
            "events",
            {"calendar_title": obj.shared_calendar.to_object.Title()},
        )
        _message_submitting_user(obj)
