from borg.localrole.interfaces import ILocalRoleProvider
from plone.app.z3cform.widget import SelectFieldWidget
from plone.autoform import directives
from plone.autoform.interfaces import IFormFieldProvider
from plone.supermodel import model
from ploneintranet.core import _
from zope import schema
from zope.component import adapter
from zope.interface import implementer
from zope.interface import provider


@provider(IFormFieldProvider)
class IReaderGroupListSupport(model.Schema):
    """Support for specifying multiple groups for read access"""

    directives.widget("reader_group_list", SelectFieldWidget, separator=",")
    reader_group_list = schema.Set(
        title=_("Reader groups"),
        required=False,
        defaultFactory=set,
        value_type=schema.Choice(
            title=_("Group id"), vocabulary="plone.app.vocabularies.Groups"
        ),
        missing_value=set(),
    )


@implementer(ILocalRoleProvider)
@adapter(IReaderGroupListSupport)
class ReaderGroupListLocalRoles:
    """Grant special roles to reader groups"""

    _granted_roles = ["Reader"]

    def __init__(self, context):
        self.context = context

    def getRoles(self, principalid):
        """Return special roles if principalid is the reader_group"""
        if principalid not in self.context.reader_group_list:
            return []
        return self._granted_roles

    def getAllRoles(self):
        """Grant special roles to the reader groups"""
        roles = []
        for reader_group in self.context.reader_group_list:
            roles.append((reader_group, self._granted_roles))
        return roles
