from Acquisition import aq_inner
from plone import api
from plone.app.event.base import get_events
from plone.app.event.base import RET_MODE_BRAINS
from plone.app.event.ical.exporter import construct_icalendar
from plone.dexterity.content import Container
from plone.event.interfaces import IICalendar
from ploneintranet import api as pi_api
from ploneintranet.core import _
from zope import schema
from zope.interface import implementer
from zope.interface import Interface


class ICentralCalendar(Interface):
    """Central calendar that lives directly in the calendar app instead of a
    workspace"""

    allow_contributions = schema.Bool(
        title=_(
            "label_central_calendar_allow_contributions",
            "Allow contributions from workspaces",
        ),
        default=False,
        required=False,
    )
    automatically_accept = schema.Bool(
        title=_(
            "label_central_calendar_automatically_accept",
            "Automatically accept all contributions",
        ),
        default=False,
        required=False,
    )


class CentralCalendar(Container):
    def get_maintainers(self):
        maintainer_ids = set()
        if self.maintainer_group_list:
            for maintainer_group in self.maintainer_group_list:
                group = pi_api.workgroup.get(maintainer_group)
                if group:
                    maintainer_ids.update(group.members)
        owner = self.getOwner()
        if owner:
            maintainer_ids.add(owner.getId())
        maintainers = (pi_api.userprofile.get(member) for member in maintainer_ids)
        return [user for user in maintainers if user is not None]

    def is_maintainer(self, userid=None):
        if userid is None:
            userid = api.user.get_current().getId()
        owner = self.getOwner()
        if owner and owner.getId() == userid:
            return True
        elif self.maintainer_group_list:
            for maintainer_group in self.maintainer_group_list:
                group = pi_api.workgroup.get(maintainer_group)
                if group and userid in group.members:
                    return True
        return False


@implementer(IICalendar)
def calendar_from_central_calendar(context):
    """Container adapter. Returns an icalendar.Calendar object from a
    Containerish context like a Folder.
    """
    context = aq_inner(context)
    nav_root = api.portal.get_navigation_root(context=context)
    path = "/".join(nav_root.getPhysicalPath())
    uid = api.content.get_uuid(obj=context)
    result = get_events(
        context, ret_mode=RET_MODE_BRAINS, expand=False, path=path, shared_calendar=uid
    )
    return construct_icalendar(context, result)
