from plone import api
from ploneintranet import api as pi_api
from ploneintranet.workspace.tests.base import BaseTestCase


class TestRemoteAdmin(BaseTestCase):
    """
    Test the remote_admin workspace field
    """

    def _set_remote_admin(self, workspace, remote_admin):
        """Replicate the code executed in the UI"""
        sidebar = api.content.get_view(
            "sidebar.settings.advanced", workspace, self.request.clone()
        )
        sidebar.request.form["remote_admin"] = remote_admin
        sidebar.request.method = "POST"
        sidebar()

    def test_remote_admin_role_propagation(self):
        """Test that the remote admin can manage the workspaces assigned to them"""
        workspace = self.portal.workspaces["demo-workspace"]
        api.content.create(id="doc1", type="Document", container=workspace)

        # Create a user and check he has no rights on any workspace
        pi_api.userprofile.create("john_doe")
        with api.env.adopt_user("john_doe"):
            self.assertListEqual(self.workspace_container.listFolderContents(), [])

        self._set_remote_admin(workspace, "john_doe")

        self.request.__annotations__.clear()
        with api.env.adopt_user("john_doe"):
            self.assertListEqual(
                self.workspace_container.listFolderContents(), [workspace]
            )
            # We also can see the doc inside
            self.assertSetEqual(
                {"demo-workspace", "doc1"},
                {x.getId for x in api.content.find(context=workspace)},
            )
        roles = api.user.get_roles(username="john_doe", obj=workspace)
        self.assertIn("TeamManager", roles)

        pi_api.userprofile.create("jane_doe")
        roles = api.user.get_roles(username="jane_doe", obj=workspace)
        self.assertNotIn("TeamManager", roles)
