from datetime import timedelta
from ploneintranet.notifications.interfaces import IProvideContextUID
from ploneintranet.notifications.sql import saconfig
from sqlalchemy import or_


def on_message_sent(message, event):
    """Log a chat message event

    Do not log the event if the another similar event has already been logged
    """
    if not saconfig.can_log_events():
        return

    session = saconfig.session()
    LoggedEvent = saconfig.LoggedEvent

    # Check if we have already notification for this chat
    # We look for logged events of this kind that have been logged in the last
    # 10 minutes or before if they are unprocessed
    existing_events = session.query(LoggedEvent).filter(
        LoggedEvent._zope_event == "chat_messages",
        LoggedEvent._context.ilike(
            IProvideContextUID(message).replace(str(message.uid), "%")
        ),
        or_(
            LoggedEvent.processed == None,  # noqa: E711
            LoggedEvent.time > saconfig.utc_now() - timedelta(minutes=10),
        ),
    )

    if existing_events.count():
        return

    saconfig.log_event(message, "chat_messages")
