from zope.interface import implements

from Products.CMFCore.utils import getToolByName

from OFS.SimpleItem import SimpleItem

from AccessControl import Unauthorized

from Products.listen.interfaces import IMemberLookup

class MemberToEmail(SimpleItem):
    """
    Implementation to convert from plone member ids to email addresses

    set up our implementation
    >>> from tests import app
    >>> from Products.listen.content.tests import DummyMembershipTool
    >>> from Products.listen.content.tests import DummyMember
    >>> mtool = DummyMembershipTool('whatever')
    >>> app.portal_membership = mtool
    >>> me = MemberToEmail(app)

    create some fake members on our fake tool
    >>> mtool.foo = DummyMember('foo', 'foo', 'foo@example.com')
    >>> mtool.bar = DummyMember('bar', 'bar', 'bar@example.com')
    >>> mtool.baz = DummyMember('baz', 'baz', 'baz@example.com')

    try converting an empty list of members
    >>> me.to_email_address([])
    []

    now try converting one member
    >>> me.to_email_address(['foo'])
    ['foo@example.com']

    and now try 3 at a time
    >>> me.to_email_address('foo bar baz'.split())
    ['foo@example.com', 'bar@example.com', 'baz@example.com']

    try going the other way: email --> memberid
    >>> me.to_memberid('foo@example.com')
    'foo'

    """
    
    implements(IMemberLookup)

    def __init__(self, context):
        self.mtool = getToolByName(context, 'portal_membership')
        self.context = context

    def _lookup_memberid(self, member_id):
        member_obj = self.mtool.getMemberById(member_id)

        if member_obj is None: return None
        try:
            return member_obj.getProperty('email', None)
        except Unauthorized, e:
            try:
                # Maybe we have CMFMember/remember, if not reraise
                return member_obj.getEmail()
            except AttributeError:
                raise e

    def to_email_address(self, tokens):
        return filter(None, map(self._lookup_memberid, tokens))

    def to_memberid(self, email):
        mems = self.mtool.searchForMembers(email=email)
        if mems:
            # is this the best way of getting the member id from a search?
            mem = mems[0]
            return mem.getId()
        else:
            return None
