from datetime import datetime
from plone import api
from plone.app.event import base as pae_base
from plone.memoize.view import memoize_contextless
from plone.restapi.interfaces import IExpandableElement
from plone.restapi.services import Service
from ploneintranet.restapi.interfaces import ISerializeToJsonSummaryCalendar
from ploneintranet.workspace.utils import parent_workspace
from zope.component import adapter
from zope.component import getMultiAdapter
from zope.interface import implementer
from zope.interface import Interface


@implementer(IExpandableElement)
@adapter(Interface, Interface)
class CalendarEvents:
    def __init__(self, context, request):
        self.context = context.aq_explicit
        self.request = request

    def __call__(self, expand=False):
        """Reply to REST/JSON requests."""
        result = {
            "calendar_events": {
                "@id": f"{self.context.absolute_url()}/@calendar_events"
            }
        }
        if not expand:
            return result

        start = self.request.form.get("start", None)
        if start:
            start = datetime.strptime(start, "%Y-%m-%d")
            start = pae_base.dt_start_of_day(start)

        end = self.request.form.get("end", None)
        if end:
            end = datetime.strptime(end, "%Y-%m-%d")
            end = pae_base.dt_end_of_day(end)

        current_workspace = parent_workspace(self.context)  # if any...
        portal = api.portal.get()
        events = pae_base.get_events(
            context=portal,
            path="/".join((current_workspace or portal).getPhysicalPath()),
            start=start,
            end=end,
            ret_mode=pae_base.RET_MODE_BRAINS,
            expand=True,
        )

        all_groups = self.all_groups
        all_workspace_paths = self.all_workspace_paths

        items = list(
            map(
                lambda it: getMultiAdapter(
                    (it, self.request), ISerializeToJsonSummaryCalendar
                )(
                    all_groups=all_groups,
                    all_workspace_paths=all_workspace_paths,
                    current_workspace=current_workspace,
                ),
                events,
            )
        )

        result["calendar_events"]["items"] = items

        self.request.response.setHeader("Content-Type", "application/json")

        return result

    @property
    @memoize_contextless
    def calendar_app(self):
        app = api.portal.get()["apps"]["calendar"]
        app_view = api.content.get_view(
            context=app, name="app-calendar", request=self.request
        )
        return app_view

    @property
    @memoize_contextless
    def all_workspace_paths(self):
        return [w.getPath() for w in self.calendar_app.get_workspaces()]

    @property
    @memoize_contextless
    def all_groups(self):
        return set(self.calendar_app.get_authenticated_groupids())


class CalendarEventsGet(Service):
    def reply(self):
        service_factory = CalendarEvents(self.context, self.request)
        return service_factory(expand=True)["calendar_events"]
