from Products.PluggableAuthService.interfaces.plugins import IPropertiesPlugin
from Products.PluggableAuthService.interfaces.plugins import IRolesPlugin

import re

COLLECTIVE_WORKSPACE_GROUPID_PATTERN = re.compile("^[A-Z][a-z]*:([a-f]|[0-9]){32}$")


def _findGroup(self, plugins, group_id, title=None, request=None):
    """Patch pas logic to find group to avoid invoking the membrane plugins
    for groups that we suspect should be only managed
    by the collective.workspaces pas plugin
    """
    is_workspace = bool(COLLECTIVE_WORKSPACE_GROUPID_PATTERN.match(group_id))

    group = self._createGroup(plugins, group_id, title)

    propfinders = plugins.listPlugins(IPropertiesPlugin)

    for propfinder_id, propfinder in propfinders:
        if is_workspace and propfinder_id == "membrane_properties":
            continue
        data = propfinder.getPropertiesForUser(group, request)
        if data:
            group.addPropertysheet(propfinder_id, data)

    ignore_plugins = ()
    if is_workspace:
        ignore_plugins = ("membrane_groups",)
    groups = self._getPAS()._getGroupsForPrincipal(
        group, request, plugins=plugins, ignore_plugins=ignore_plugins
    )
    group._addGroups(groups)

    rolemakers = plugins.listPlugins(IRolesPlugin)

    for rolemaker_id, rolemaker in rolemakers:
        if is_workspace and rolemaker_id == "membrane_roles":
            continue
        roles = rolemaker.getRolesForPrincipal(group, request)
        if roles:
            group._addRoles(roles)

    group._addRoles(["Authenticated"])

    return group.__of__(self)
