# -*- coding: utf-8 -*-
# Copyright (c) 2009 Michael Howitz
# See also LICENSE.txt
# $Id: sources.py 969 2009-01-25 14:42:26Z mac $

import gocept.reference.interfaces
import zc.sourcefactory.basic
import zc.sourcefactory.contextual
import zope.component
import zope.securitypolicy.interfaces
import zope.app.authentication.principalfolder
import zope.security.proxy

import icemac.addressbook.interfaces

class RoleSource(zc.sourcefactory.basic.BasicSourceFactory):
    """A source for all global roles."""

    def getValues(self):
        roles = zope.component.getAllUtilitiesRegisteredFor(
            zope.securitypolicy.interfaces.IRole)
        names = [r.id
                 for r in roles
                 if r.id.startswith('icemac.addressbook.global.')]
        return sorted(names)

    def getTitle(self, value):
        role = zope.component.getUtility(
            zope.securitypolicy.interfaces.IRole, name=value)
        return role.title

role_source = RoleSource()


class Persons(zc.sourcefactory.contextual.BasicContextualSourceFactory):
    """Persons in addressbook."""

    def getValues(self, context):
        root = icemac.addressbook.principals.interfaces.IRoot(context)
        insecured_context = zope.security.proxy.removeSecurityProxy(context)
        # When editing a user we need this users person in list, as
        # the person on user is not changeable we need only to return
        # this person.
        if isinstance(insecured_context,
                      icemac.addressbook.principals.principals.Principal):
            yield context.person
            return

        for person in root.values():
            if getattr(person.default_email_address, 'email', None):
                # show only persons which are not yet users
                reftarget = gocept.reference.interfaces.IReferenceTarget(person)
                if reftarget.is_referenced(recursive=False):
                    # XXX must check for other types of reference here
                    continue
                yield person

    def getTitle(self, context, value):
        return icemac.addressbook.interfaces.ITitle(value)

persons = Persons()
