import sys
from types import *

from DateTime import DateTime

def _convert( self, value, default=None ):
    """Convert Date/Time value to our internal representation"""
    # XXX: Code patched 20/May/2003 by Kiran Jonnalagadda to
    # convert dates to UTC first.
    if isinstance( value, DateTime ):
        t_tup = value.toZone('UTC').parts()
    elif type( value ) in (FloatType, IntType):
        t_tup = time.gmtime( value )
    elif type( value ) is StringType:
        t_obj = DateTime( value ).toZone('UTC')
        t_tup = t_obj.parts()
    else:
        return default

    yr = t_tup[0]
    mo = t_tup[1]
    dy = t_tup[2]
    hr = t_tup[3]
    mn = t_tup[4]

    t_val = ( ( ( ( yr * 12 + mo ) * 31 + dy ) * 24 + hr ) * 60 + mn )

    if isinstance(t_val, long):
        # t_val must be IntType, not LongType
        #XXX: We return maxint here instead of raising an overflowerror. This
        #     way we can index far future dates in CMF without problem
        return sys.maxint
        raise OverflowError, (
            "%s is not within the range of indexable dates (index: %s)"
            % (value, self.id))

    return t_val


try:
    from Products.PluginIndexes.DateIndex.DateIndex import DateIndex
    DateIndex._convert = _convert
except:
    raise AssertionError('Could not patch required DateIndex')
    pass
