from collective.workspace.interfaces import IWorkspace
from plone import api
from ploneintranet import api as pi_api
from ploneintranet.workspace.testing import PLONEINTRANET_WORKSPACE_INTEGRATION_TESTING
from unittest import TestCase
from zope.event import notify
from zope.lifecycleevent import ObjectModifiedEvent


class TestPIRecursiveGroupsPluginWS(TestCase):
    """Test installation of ploneintranet.userprofile into Plone."""

    layer = PLONEINTRANET_WORKSPACE_INTEGRATION_TESTING

    def setUp(self):
        self.app = self.layer["app"]
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]

    def test_recursive_groups(self):
        """Check if our recursive groups plugin is working properly"""
        pi_api.userprofile.create("foo")
        plugin = self.portal.acl_users.pi_recursive_groups

        foo = api.user.get("foo")

        def _check_foo_groups():
            return set(plugin.getGroupsForPrincipal(foo, request=self.request.clone()))

        ws = self.portal.workspaces["demo-workspace"]
        notify(ObjectModifiedEvent(ws))

        wsadapter = IWorkspace(ws)

        self.assertSetEqual(_check_foo_groups(), set())

        wsadapter.add_to_team("foo")
        self.assertSetEqual(
            _check_foo_groups(), {"Consumers:%s" % ws.UID(), "Members:%s" % ws.UID()}
        )

        ws.participant_policy = "producers"
        self.assertSetEqual(
            _check_foo_groups(), {"Producers:%s" % ws.UID(), "Members:%s" % ws.UID()}
        )

    def test_recursive_groups_with_quaive_group(self):
        """Check if our recursive groups plugin is working properly
        when the quaive.groups behavior is enabled
        """
        # Now enable the behavior and verify that we have an additional group
        pt = api.portal.get_tool("portal_types")
        fti = pt["ploneintranet.workspace.workspacefolder"]
        fti._updateProperty("behaviors", fti.behaviors[:] + ("quaive.group",))

        pi_api.userprofile.create("foo")
        plugin = self.portal.acl_users.pi_recursive_groups

        foo = api.user.get("foo")

        def _check_foo_groups():
            return set(plugin.getGroupsForPrincipal(foo, request=self.request.clone()))

        ws = self.portal.workspaces["demo-workspace"]
        notify(ObjectModifiedEvent(ws))

        wsadapter = IWorkspace(ws)

        self.assertSetEqual(_check_foo_groups(), set())

        wsadapter.add_to_team("foo")
        self.assertSetEqual(
            _check_foo_groups(),
            {ws.getId(), "Consumers:%s" % ws.UID(), "Members:%s" % ws.UID()},
        )

        ws.participant_policy = "producers"
        self.assertSetEqual(
            _check_foo_groups(),
            {ws.getId(), "Producers:%s" % ws.UID(), "Members:%s" % ws.UID()},
        )
