from collective.workspace.interfaces import IWorkspace
from io import BytesIO
from openpyxl import load_workbook
from plone import api
from ploneintranet.workspace.testing import PLONEINTRANET_WORKSPACE_INTEGRATION_TESTING
from ploneintranet.workspace.tests.base import BaseTestCase


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

    layer = PLONEINTRANET_WORKSPACE_INTEGRATION_TESTING

    def setUp(self):
        self.app = self.layer["app"]
        self.portal = self.layer["portal"]
        self.request = self.portal.REQUEST
        super().setUp()
        self.private_workspace = api.content.create(
            self.workspace_container,
            "ploneintranet.workspace.workspacefolder",
            title="Private Workspace",
        )
        IWorkspace(self.private_workspace).add_to_team("demo")
        self.view = api.content.get_view(
            context=self.portal,
            name="workspace-membership-report.xls",
            request=self.request,
        )

    def test_principals_by_role(self):
        admins = self.view.principals_by_role(self.private_workspace)["Admin"]
        self.assertEqual(admins, ["test_user_1_"])

    def test_workspace_details(self):
        details, roles = self.view.workspace_details_and_roles(self.private_workspace)
        self.assertFalse(details["visible_to_intranet_users"])
        self.assertEqual(details["join_policy"], "admin"),
        self.assertEqual(details["title"], "Private Workspace")
        self.assertEqual(details["participant_policy"], "consumers")
        self.assertFalse(details["accessible_to_intranet_users"])
        self.assertEqual(details["Admin"], "test_user_1_")
        self.assertEqual(details["Consume"], "demo")
        self.assertEqual(details["id"], "private-workspace")
        self.assertEqual(details["all_members"], "demo, test_user_1_")
        self.assertSetEqual(set(roles), {"Admin", "Consume"})

    def test_to_excel(self):
        data = [
            {"id": "first", "title": "First", "Admin": "test_user_1_"},
            {"id": "second", "title": "Second"},
        ]
        xl = self.view.to_excel(data, ["Admin"])
        workbook = load_workbook(BytesIO(xl))
        sheet = workbook.active
        self.assertEqual(sheet.cell(1, 1).value, "ID")
        self.assertEqual(sheet.cell(2, 7).value, "test_user_1_")
        self.assertEqual(sheet.cell(3, 1).value, "second")
