from collective.workspace.interfaces import IWorkspace
from plone.app.uuid.utils import uuidToCatalogBrain
from plone.memoize.view import memoize
from plone.memoize.view import memoize_contextless
from ploneintranet.core import _
from ploneintranet.microblog.browser.panel_users import Users
from ploneintranet.workspace.config import INTRANET_USERS_GROUP_ID
from ploneintranet.workspace.utils import parent_workspace
from zope.i18n import translate


class WorkspaceUsers(Users):
    """Customize the panel-users panel to search only in the workspace
    members."""

    @property
    @memoize
    def valid_user_uids(self):
        """Find the user UIDS in order to limit the search."""
        descendants = set()
        context_uid = self.context.UID()
        for group_uid_template in (
            "collective.workspace:Members:{0}",
            "collective.workspace:Guests:{0}",
        ):
            descendants.update(
                self.pas_view.descendants(group_uid_template.format(context_uid))
            )
        return [
            descendant.rpartition(":")[-1]
            for descendant in descendants
            if descendant.startswith("userprofile")
        ]

    @property
    def filters_users(self):
        """Limit the user search to the workspace members."""
        filters = super().filters_users.copy()
        if self.context.accessible_to_intranet_users:
            return filters
        filters["UID"] = self.valid_user_uids
        return filters

    def is_group(self, item):
        return (
            super().is_group(item)
            or item.portal_type == "ploneintranet.workspace.workspacefolder"
        )

    def num_users(self, item):
        if item.portal_type != "ploneintranet.workspace.workspacefolder":
            return super().num_users(item)

        member_ids = IWorkspace(self.context).members
        if INTRANET_USERS_GROUP_ID not in member_ids:
            return len(self.valid_user_uids)

        num = 0
        for member_id in member_ids:
            if member_id != INTRANET_USERS_GROUP_ID:
                pas_uid = self.pas_view.principalname2uid(member_id)
                if pas_uid.startswith("userprofile:"):
                    num += 1
                else:
                    num += len(self.pas_view.descendants(pas_uid))
        return num

    def pas_uid(self, item):
        if item.portal_type == "ploneintranet.workspace.workspacefolder":
            return f"workspace:{item.UID}"
        return super().pas_uid(item)

    def title(self, item):
        if item.portal_type == "ploneintranet.workspace.workspacefolder":
            return self.workspace_title_translated
        return super().title(item)

    @property
    @memoize_contextless
    def workspace_title_translated(self):
        return translate(_("Workspace"), context=self.request)

    @property
    def results(self):

        extra_results = []

        workspace_title_translated = self.workspace_title_translated
        workspace = parent_workspace(self.context)
        if workspace is not None and (
            not self.query
            or self.query.lower() in "workspace"
            or self.query.lower() in workspace_title_translated.lower()
        ):
            brain = uuidToCatalogBrain(workspace.UID())
            extra_results.append(brain)

        return extra_results + super().results
