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 Products.CMFCore.indexing import processQueue
from Products.membrane.interfaces import IGroup
from unittest import TestCase
from zope.globalrequest import getRequest


class TestWorkspaceWorkgroups(TestCase):

    layer = PLONEINTRANET_WORKSPACE_INTEGRATION_TESTING

    def setUp(self):
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]
        self.workspace = api.content.create(
            container=self.portal.workspaces,
            id="testws",
            type="ploneintranet.workspace.workspacefolder",
        )
        self.userprofile = pi_api.userprofile.create(
            username="johndoe@doe.com", email="johndoe@doe.com"
        )
        self.workgroup = pi_api.workgroup.create(
            canonical="Test workgroup",
            title="Test workgroup",
            description="",
            members={"johndoe@doe.com"},
            email="testworkgroup@example.com",
        )
        IWorkspace(self.workspace).add_to_team(self.workgroup.canonical)

    def test_workgroup_security(self):
        """Check that we can enable the workspace is a group feature"""
        self.assertTrue(
            api.user.has_permission("View", user=self.userprofile, obj=self.workspace)
        )
        with self.assertRaises(TypeError):
            IGroup(self.workspace)
        # Now enable the behavior and verify that we have group that knows itsmembers
        pt = api.portal.get_tool("portal_types")
        fti = pt["ploneintranet.workspace.workspacefolder"]
        fti._updateProperty("behaviors", fti.behaviors[:] + ("quaive.group",))
        group = IGroup(self.workspace)
        self.assertSetEqual(
            set(group.getGroupMembers()), {"test_user_1_", "Test workgroup"}
        )

    def test_workspace_owner_should_be_an_admin(self):
        """When fiddling with the workspace membership,
        we want to be sure that is the workspace owner loses the admin status
        the ownership of the workspace will change
        """
        ownerid = self.workspace.getOwner().getId()
        self.assertEqual(ownerid, "test_user_1_")

        adapter = IWorkspace(self.workspace)

        def remove_from_team(principalid):
            """Helper function to clear caches before removing users
            from the workspace team
            """
            # Flush catalog and clear memoize cache
            processQueue()
            getRequest().__annotations__.clear()
            adapter.remove_from_team(principalid)

        # Check that removing the current owner
        # will pick another admin as owner
        adapter.add_to_team("johndoe@doe.com", groups={"Admins"})
        # and we remove the old owner
        remove_from_team(ownerid)
        # Now the workspace owner is johndoe
        ownerid = self.workspace.getOwner().getId()
        self.assertEqual(ownerid, "johndoe@doe.com")

        # Check that removing the current owner
        # will pick a user in the admins group
        pi_api.userprofile.create("janedoe@doe.com")
        pi_api.workgroup.create(title="Admins group", members=["janedoe@doe.com"])
        adapter.add_to_team("admins-group", groups={"Admins"})
        remove_from_team("johndoe@doe.com")
        ownerid = self.workspace.getOwner().getId()
        self.assertEqual(ownerid, "janedoe@doe.com")

        # Check that if not admin is defined the owner
        # will be the current user, which is supposed to have enough power
        # to edit the team membership
        remove_from_team("admins-group")
        ownerid = self.workspace.getOwner().getId()
        self.assertEqual(ownerid, api.user.get_current().getUserId())
