"""
$Id: __init__.py,v 1.2 2005/02/26 17:56:10 sidnei Exp $
"""

from zope.interface import implements
from zope.interface.interface import Interface, InterfaceClass
from zope.schema import TextLine, Text, List, Int, Bool, Float
from zope.component.interfaces import IUtilityService
from zope.component.exceptions import ComponentLookupError
from Products.Archetypes.public import listTypes
from Products.Archetypes.public import StringField, DateTimeField
from Products.Archetypes.public import TextField, LinesField
from Products.Archetypes.public import IntegerField, BooleanField
from Products.Archetypes.public import ImageField, FileField
from Products.Archetypes.public import ReferenceField, FloatField
from Products.Archetypes.public import FixedPointField
from Products.Five.interfaces import IUtilityProvider

_map = {TextField:TextLine,
        LinesField:TextLine,
        IntegerField:TextLine,
        BooleanField:TextLine,
        StringField:TextLine,
        DateTimeField:TextLine,
        ImageField:TextLine,
        FileField:TextLine,
        ReferenceField:TextLine,
        FloatField:TextLine,
        FixedPointField:TextLine,
        }

def convert(field):
    factory = _map[field.__class__]
    return factory(title=unicode(field.widget.label),
                   description=unicode(field.widget.description))

def toZope3Schema(schema, name):
    fields = {}
    name = name.split('.')[-1]
    for field in schema.fields():
        fields[field.getName()] = convert(field)
    return InterfaceClass('I%s' % name, (Interface,), fields)

_import_chickens = {}, {}, ("*",) # dead chickens needed by __import__

def resolveName(name, default=None):
    # Split off object name:
    names = name.split('.')
    oname, mname = names[-1], '.'.join(names[:-1])

    # Import the module
    if not mname:
        # Just got a single name. Must me a module
        mname = oname
        oname = ''

    try:
        mod = __import__(mname, *_import_chickens)
    except ImportError:
        return default

    if not oname:
        # see not mname case above
        return mod

    try:
        return getattr(mod, oname)
    except AttributeError:
        # No such name, maybe it's a module that we still need to import
        try:
            return __import__(mname+'.'+oname, *_import_chickens)
        except ImportError:
            return default

class UtilityProvider:
    implements(IUtilityProvider)

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

    def queryUtility(self, interface, name='', default=None):
        """See IUtilityService interface
        """
        klass = resolveName(name, default=None)
        if klass is None:
            return default
        # XXX Better way of getting at the schema?
        schema = klass.schema
        return toZope3Schema(schema, name)

    def getUtilitiesFor(self, interface):
        for t in listTypes():
            yield toZope3Schema(t['schema'], t['klass'].__name__)
