from borg.localrole.interfaces import ILocalRoleProvider
from ploneintranet.todo.behaviors import ITodo
from zope.component import adapter
from zope.interface import implementer


@implementer(ILocalRoleProvider)
@adapter(ITodo)
class TodoAssigneeLocalRoleAdapter:
    """This adapter is invoked by the borg_localroles plugin to grant the
    Reader and Assignee roles to the assignee.
    """

    _granted_roles = ["Reader", "Assignee"]

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

    def getRoles(self, principalid):
        """Return the reader role if principalid is assignee or initiator"""
        if principalid == self.context.assignee:
            return self._granted_roles
        elif principalid == self.context.initiator:
            return ["Reader"]
        return []

    def getAllRoles(self):
        """Grant the assignee and initiator the reader role"""
        mapping = {}
        assignee = self.context.assignee
        if assignee:
            mapping[assignee] = self._granted_roles
        initiator = self.context.initiator
        if initiator and initiator != assignee:
            mapping[initiator] = ["Reader"]
        return list(mapping.items())
