from AccessControl import ClassSecurityInfo
from AccessControl.class_init import InitializeClass
from plone import api
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
from Products.PluggableAuthService.utils import classImplements
from zope.globalrequest import getRequest
from zope.interface import Interface


class IPIRecursiveGroupsPlugin(Interface):
    """Marker interface."""


manage_addPIRecursiveGroupsPluginForm = PageTemplateFile(
    "www/pirgpAdd", globals(), __name__="manage_addPIRecursiveGroupsPluginForm"
)


def addPIRecursiveGroupsPlugin(dispatcher, id, title=None, REQUEST=None):
    """Add a PIRecursiveGroupsPlugin to a Pluggable Auth Service."""

    rgp = PIRecursiveGroupsPlugin(id, title)
    dispatcher._setObject(rgp.getId(), rgp)

    if REQUEST is not None:
        REQUEST["RESPONSE"].redirect(
            "%s/manage_workspace"
            "?manage_tabs_message="
            "PIRecursiveGroupsPlugin+added." % dispatcher.absolute_url()
        )


class PIRecursiveGroupsPlugin(BasePlugin):
    """PAS plugin for recursively flattening a collection of groups"""

    meta_type = "PloneIntranet Recursive Groups Plugin"

    security = ClassSecurityInfo()

    def __init__(self, id, title=None):

        self._id = self.id = id
        self.title = title

    @security.private
    def getGroupsForPrincipal(self, user, request=None):
        if not request:
            request = getRequest()
        if not request:
            return ()
        pas_view = api.content.get_view("pas_view", api.portal.get(), request)
        return pas_view.get_recursive_group_names(user)


classImplements(PIRecursiveGroupsPlugin, IPIRecursiveGroupsPlugin, IGroupsPlugin)

InitializeClass(PIRecursiveGroupsPlugin)
