""" Python part of the low-level DateTime[Delta] type implementation.

    (c) 1998, Copyright Marc-Andre Lemburg; All Rights Reserved.
    See the documentation for further information on copyrights,
    or contact the author (mal@lemburg.com).
"""
# Import C extension module
from mxDateTime import *
from mxDateTime import __version__

# Singletons
oneSecond = DateTimeDelta(0,0,0,1)
oneMinute = DateTimeDelta(0,0,1)
oneHour = DateTimeDelta(0,1)
oneDay = DateTimeDelta(1)
oneWeek = DateTimeDelta(7)
Epoch = DateTimeFromAbsDateTime(1,0)

# Shortcuts for pickle (reduces the pickle's length)
def _DT(absdate,abstime):
    return DateTimeFromAbsDateTime(absdate,abstime)
def _DTD(seconds):
    return DateTimeDeltaFromSeconds(seconds)

# Module init
class modinit:

    global _time,_string
    import time,string
    _time = time
    _string = string

    ### Register the two types
    import copy_reg
    def pickle_DateTime(d):
	return _DT,(d.absdate,d.abstime)
    def pickle_DateTimeDelta(d):
	return _DTD,(d.seconds,)
    copy_reg.pickle(DateTimeType,
		    pickle_DateTime,
		    _DT)
    copy_reg.pickle(DateTimeDeltaType,
		    pickle_DateTimeDelta,
		    _DTD)

del modinit

# Aliases and functions to make 'from DateTime import *' work much
# like 'from time import *'

def localtime(ticks=None,
	      # Locals:
	      time=_time.time,float=float,localtime=_time.localtime,
	      round=round,int=int,DateTime=DateTime):

    """localtime(ticks=None)

    Construct a DateTime instance using local time from ticks.
    If ticks are not given, it defaults to the current time.
    The result is similar to time.localtime(). Fractions of a
    second are rounded to the nearest micro-second."""

    if ticks is None:
	ticks = time()
    else:
	ticks = float(ticks)
    Y,M,D,h,m,s = localtime(ticks)[:6]
    s = round(s + (ticks - int(ticks)),6)
    return DateTime(Y,M,D,h,m,s)

def gmtime(ticks=None,
	   # Locals:
	   time=_time.time,float=float,gmtime=_time.gmtime,
	   round=round,int=int,DateTime=DateTime):

    """gmtime(ticks=None)

    Construct a DateTime instance using UTC time from ticks.
    If ticks are not given, it defaults to the current time.
    The result is similar to time.gmtime(). Fractions of a
    second are rounded to the nearest micro-second."""

    if ticks is None:
	ticks = time()
    else:
	ticks = float(ticks)
    Y,M,D,h,m,s = gmtime(ticks)[:6]
    s = round(s + (ticks - int(ticks)),6)
    return DateTime(Y,M,D,h,m,s)

def mktime(year,month,day,hour,minute,second,dow,doy,dst,
	   # Locals:
	   DateTime=DateTime):

    """mktime(year,month,day,hour,minute,second,dow,doy,dst)

    Alias for DateTime that excepts additional arguments to be
    call compatible with time.mktime(). Note that the arguments dow,doy
    and dst are not used in any way."""

    return DateTime(year,month,day,hour,minute,second)

def ctime(datetime):

    """ctime(datetime)

    Returns a string representation of the given DateTime instance
    using the current locale's default settings."""

    return datetime.strftime('%c')

def today(hour=0,minute=0,second=0.0,
	  # Locals:
	  localtime=_time.localtime,time=_time.time,DateTime=DateTime):

    """today(hour=0,minute=0,second=0.0)

    Returns a DateTime instance for today (in local time) at the
    given time (defaults to midnight)."""

    Y,M,D = localtime(time())[:3]
    return DateTime(Y,M,D,hour,minute,second)

def TimeDelta(hours=0.0,minutes=0.0,seconds=0.0,
	      # Locals:
	      DateTimeDelta=DateTimeDelta):

    """TimeDelta(hours=0.0,minutes=0.0,seconds=0.0)

    Returns a DateTimeDelta-object reflecting the given
    time delta. Seconds can be given as float to indicate fractions."""

    return DateTimeDelta(0,hours,minutes,seconds)

# Choose the implementation for gmticks()... the timegm() C API
# is preferred over the mktime() approach (which may fail on some
# platforms).

if hasattr(Epoch,'gmticks'):

    def gmticks(datetime):

	"""gmticks(datetime)

	Returns a ticks value based on the values stored in
	datetime under the assumption that they are given
	in UTC, rather than local time."""

	return datetime.gmticks()

    def tz_offset(datetime,
		  # Locals:
		  oneSecond=oneSecond):

	"""tz_offset(datetime)

	Returns a DateTimeDelta instance representing the UTC offset
	for datetime assuming that the stored values refer to local
	time. If you subtract this value from datetime, you'll get UTC
	time."""

	return (datetime.gmticks() - datetime.ticks())*oneSecond

    # Note: The method used for calculating the tz offset may fail
    # near the DST switching time. I haven't put much thought into
    # this yet, but some experiments show that it continues to
    # work even during the switching periods. This is, of course, no proof.

else:

    def gmticks(datetime):

	"""gmticks(datetime)

	Returns a ticks value based on the values stored in
	datetime under the assumption that they are given
	in UTC, rather than local time."""
	try:
	    return datetime.ticks(_time.timezone,0)
	except SystemError:
	    raise SystemError,'gmticks() is not supported on this platform'

    def tz_offset(datetime,
		  # Locals:
		  oneSecond=oneSecond):

	"""tz_offset(datetime)

	Returns a DateTimeDelta instance representing the UTC offset
	for datetime assuming that the stored values refer to local
	time. If you subtract this value from datetime, you'll get UTC
	time."""

	local = datetime.ticks()
	try:
	    gmt = datetime.ticks(_time.timezone,0)
	except SystemError:
	    raise SystemError,'tz_offset() is not supported on this platform'
	return (gmt - local)*oneSecond

def gm2local(datetime):

    """ Convert a DateTime instance holding UTC time to a DateTime
        instance using local time.
    """
    return localtime(gmticks(datetime))

def local2gm(datetime):

    """ Convert a DateTime instance holding local time to a DateTime
        instance using UTC time.
    """
    return gmtime(datetime.ticks())

###

class RelativeDateTime:

    """RelativeDateTime(years=0,months=0,days=0,year=0,month=0,day=0,
		      hours=0,minutes=0,seconds=0,
		      hour=None,minute=None,second=None)

       Returns a RelativeDateTime instance for the specified relative
       time. The constructor handles keywords, so you'll only have to
       give those parameters which should be changed when you add the
       relative to an absolute DateTime instance. Absolute values passed
       to the constructor will override delta values of the same type.

       Adding RelativeDateTime instances is supported with the
       following rules: deltas will be added together, right side
       absolute values override left side ones.

       Adding RelativeDateTime instances to DateTime instances will
       return DateTime instances with the appropriate calculations
       applied, e.g. to get a DateTime instance for the first of next
       month, you'd call now()+RelativeDateTime(months=+1,day=01).

    """
    years = 0
    months = 0
    days = 0
    year = 0
    month = 0
    day = 0
    hours = 0
    minutes = 0
    seconds = 0
    hour = None
    minute = None
    second = None

    def __init__(self,years=0,months=0,days=0,year=0,month=0,day=0,
		      hours=0,minutes=0,seconds=0,
		      hour=None,minute=None,second=None):
	
	self.years = years
	self.months = months
	self.days = days
	self.year = year
	self.month = month
	self.day = day
	self.hours = hours
	self.minutes = minutes
	self.seconds = seconds
	self.hour = hour
	self.minute = minute
	self.second = second

    def __add__(self,other):

	if isinstance(other,RelativeDateTime):
	    # RelativeDateTime (self) + RelativeDateTime (other)

	    r = RelativeDateTime()
	    # date deltas
	    r.years = self.years + other.years
	    r.months = self.months + other.months
	    r.days = self.days + other.days
	    # absolute entries of other override those in self, if given
	    r.year = other.year or self.year
	    r.month = other.month or self.month
	    r.day = other.day or self.day
	    # time deltas
	    r.hours = self.hours + other.hours
	    r.minutes = self.minutes + other.minutes
	    r.seconds = self.seconds + other.seconds
	    # absolute entries of other override those in self, if given
	    r.hour = other.hour or self.hour
	    r.minute = other.minute or self.minute
	    r.second = other.second or self.second
	    return r

	else:
	    raise TypeError,"can't add the two types"

    def __radd__(self,other,
		 # Locals:
		 None=None,isinstance=isinstance,DateTime=DateTime):

	if isinstance(other,DateTimeType):
	    # DateTime (other) + RelativeDateTime (self)

	    # date
	    year = self.year or (other.year + self.years)
	    month = self.month or (other.month + self.months)
	    day = self.day or (other.day + self.days)
	    # time
	    hour = self.hour
	    if hour is None:
		hour = other.hour + self.hours
	    minute = self.minute
	    if minute is None:
		minute = other.minute + self.minutes
	    second = self.second
	    if second is None:
		second = other.second + self.seconds

	    #print 'first try:',year, month, day, hour, minute, second
	    if month > 0 and day > 0:
		try:
		    return DateTime(year, month, day, hour, minute, second)
		except RangeError:
		    pass
	    # Refit into proper ranges:
	    if month < 1 or month > 12:
		month = month - 1
		year = year + month / 12
		month = month % 12 + 1
	    #print 'second try:',year, month, day, hour, minute, second
	    return DateTime(year, month, 1) + \
		   DateTimeDelta(day-1,hour,minute,second)
	else:
	    raise TypeError,"can't add the two types"

    def __sub__(self,other):

	if isinstance(other,RelativeDateTime):
	    # RelativeDateTime (self) - RelativeDateTime (other)

	    r = RelativeDateTime()
	    # date deltas
	    r.years = self.years - other.years
	    r.months = self.months - other.months
	    r.days = self.days - other.days
	    # absolute entries of other override those in self, if given
	    r.year = other.year or self.year
	    r.month = other.month or self.month
	    r.day = other.day or self.day
	    # time deltas
	    r.hours = self.hours - other.hours
	    r.minutes = self.minutes - other.minutes
	    r.seconds = self.seconds - other.seconds
	    # absolute entries of other override those in self, if given
	    r.hour = other.hour or self.hour
	    r.minute = other.minute or self.minute
	    r.second = other.second or self.second

	    return r

	else:
	    raise TypeError,"can't subtract the two types"

    def __rsub__(self,other,
		 # Locals:
		 None=None,isinstance=isinstance,DateTime=DateTime):

	if isinstance(other,DateTimeType):
	    # DateTime (other) - RelativeDateTime (self)

	    # date
	    year = self.year or (other.year - self.years)
	    month = self.month or (other.month - self.months)
	    day = self.day or (other.day - self.days)

	    # time
	    hour = self.hour
	    if hour is None:
		hour = other.hour - self.hours
	    minute = self.minute
	    if minute is None:
		minute = other.minute - self.minutes
	    second = self.second
	    if second is None:
		second = other.second - self.seconds

	    #print 'first try:',year, month, day, hour, minute, second
	    if month > 0 and day > 0:
		try:
		    return DateTime(year, month, day, hour, minute, second)
		except RangeError:
		    pass
	    # Refit into proper ranges:
	    if month < 1 or month > 12:
		month = month - 1
		year = year + month / 12
		month = month % 12 + 1
	    #print 'second try:',year, month, day, hour, minute, second
	    return DateTime(year, month, 1) + \
		   DateTimeDelta(day-1,hour,minute,second)
	else:
	    raise TypeError,"can't subtract the two types"

    def __str__(self,

		join=_string.join):

	l = []
	append = l.append
	if self.year:
	    append('%04i-' % self.year)
	elif self.years:
	    append('(%0+5i)-' % self.years)
	else:
	    append('YYYY-')
	if self.month:
	    append('%02i-' % self.month)
	elif self.months:
	    append('(%0+3i)-' % self.months)
	else:
	    append('MM-')
	if self.day:
	    append('%02i ' % self.day)
	elif self.days:
	    append('(%0+3i) ' % self.days)
	else:
	    append('DD ')
	append(' ')
	if self.hour is not None:
	    append('%02i:' % self.hour)
	elif self.hours:
	    append('(%0+3i):' % self.hours)
	else:
	    append('HH:')
	if self.minute is not None:
	    append('%02i:' % self.minute)
	elif self.minutes:
	    append('(%0+3i):' % self.minutes)
	else:
	    append('MM:')
	if self.second is not None:
	    append('%02i' % self.second)
	elif self.seconds:
	    append('(%0+3i)' % self.seconds)
	else:
	    append('SS')
	return join(l,'')

# Aliases
utctime = gmtime
utcticks = gmticks
utc2local = gm2local
local2utc = local2gm
DateTimeFromTicks = localtime
now = localtime
Date = DateTime
Time = TimeDelta
Timestamp = DateTime
RelativeDate = RelativeDateTime
