from plone import api
from plone.app.contenttypes.interfaces import IEvent
from plone.app.event.base import localized_now
from plone.memoize.view import memoize_contextless
from plone.tiles import Tile
from ploneintranet.core import _
from ploneintranet.search.interfaces import ISiteSearch
from scorched.dates import solr_date
from zope.component import getUtility
from zope.i18nmessageid import MessageFactory

pl_message = MessageFactory("plonelocales")


class EventsTile(Tile):
    title = _("label_title_app_calendar", default="Calendar")

    @property
    @memoize_contextless
    def userid(self):
        return api.user.get_current().getId()

    @property
    @memoize_contextless
    def base_query(self):
        now = localized_now()
        query = {"object_provides": IEvent.__identifier__, "end__gt": solr_date(now)}
        if self.data.get("SearchableText", ""):
            query["SearchableText"] = self.data["SearchableText"] + "*"
        return query

    @property
    def search_events(self):
        search_util = getUtility(ISiteSearch)
        return search_util.query

    def _events(self, query):
        """
        Return upcoming events, potentially filtered by invitation status
        and/or search term
        """
        query.update(self.base_query)
        upcoming_events = self.search_events(filters=query, sort="start")
        return list(filter(None, (ev.getObject() for ev in upcoming_events)))

    def my_events(self):
        """query returning only events where I am invited"""
        query = {"invitees": [self.userid]}
        return self._events(query)[:5]

    def upcoming_events(self):
        """
        Return upcoming events, potentially filtered by invitation status
        and/or search term
        limited to 4
        """
        query = {"-invitees": [self.userid]}
        return self._events(query)[:4]
