# -*- coding: latin-1 -*-
""" 
   Copyright (C) 2001-2004 PimenTech SARL (http://www.pimentech.net)

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.  
"""

from DateTime import *

en_time = (['year', 'years'], ['month', 'months'], ['day', 'days'], ['hour', 'hours'], ['minute', 'minutes'], ['second', 'seconds'])
en_time_short = (['yr', 'ys'], ['mth', 'mhs'], ['day', 'dys'], ['hr', 'hs'], ['mn', 'mn'], ['sc', 'sc'])
fr_time = (['an', 'ans'], ['mois', 'mois'], ['jour', 'jours'], ['heure', 'heures'], ['minute', 'minutes'], ['seconde', 'secondes'])
fr_time_short = (['an', 'ans'], ['mo', 'mos'], ['jr', 'js'], ['hr', 'hs'], ['mn', 'mn'], ['sc', 'sc'])

day_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
day_month_bis = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

def is_bissextile(year):
	if year % 4 and not year % 100 or year % 400:
		return 1
	return 0


def add_month(date, number):
	if number > 12 or number < -12:
		raise "Number out of range"
	(d, m, y) = map(int, date.strftime('%d/%m/%Y').split('/'))
	m += number
	if m>12:
		m = m % 12
		y += 1
	elif m == 0:
		m = 12
		y -= 1
	elif m < 0:
		m = m % 12
		y -= 1
	return DateTime(y, m, d)
	

class Age:
	"""
	Calculate age from a DateTime with different precisions.
	precision = integer ; how much you want, zero is for all values : from year to second
	"""
	
	def __init__(self, datetime, precision=0, now=0):
		self.datetime = datetime
		if not now:
			self.now = DateTime()
		else:
			self.now = now
		self.precision = precision
		self.age = ()

	def _age_calculate(self):
		"private"
		diff_year = diff_month = diff_day = diff_hour = diff_minute = diff_second = 0

		diff_second = int(self.now.second() - (diff_second+self.datetime.second()))
		if diff_second < 0:
			diff_second += 60
			diff_minute += 1

		diff_minute = self.now.minute() - (diff_minute+self.datetime.minute())
		if diff_minute < 0:
			diff_minute += 60
			diff_second += 1

		diff_hour = self.now.hour() - (diff_hour+self.datetime.hour())
		if diff_hour < 0:
			diff_hour += 24
			diff_day += 1

		diff_day = self.now.day() - (diff_day+self.datetime.day())
		if diff_day < 0:
			if is_bissextile(self.datetime.year()):
				diff_day += day_month_bis[self.datetime.month()-1]
			else:
				diff_day += day_month[self.datetime.month()-1]
			diff_month += 1

		diff_month = self.now.month() - (diff_month+self.datetime.month())
		if diff_month < 0:
			diff_month += 12
			diff_year += 1

		diff_year = self.now.year() - (diff_year+self.datetime.year())

		self.age = (diff_year, diff_month, diff_day, diff_hour, diff_minute, diff_second)
		
	def getAge(self):
		"calculate precision and return the list of age"
		age = []
		if self.age == ():
			self._age_calculate()
		if self.precision == 0:
			self.precision = 6
		precision = self.precision
		
		for time_c in self.age:
			if precision and time_c == 0 and self.precision != precision:
				precision -= 1
				age.append(0)
			elif precision and time_c == 0 and self.precision == precision:
				age.append(0)
			elif precision == 0:
				age.append(0)
			else:
				precision -= 1
				age.append(time_c)
		return age

	def getFirst(self):
		"return the number of the first none null value of age"
		if self.age == ():
			self._age_calculate()
		i = 1
		for time_c in self.age:
			if time_c != 0:
				return i
			i += 1
		return 0
		
	def changePrecision(self, precision):
		"change precision for getAge "
		self.precision = precision

	def format(self, language):
		"pseudo multi-lingual string format"
		if language == 'fr':
			time_c = fr_time_short
		elif language == 'en':
			time_c = en_time_short
		elif language == 'FR':
			time_c = fr_time
		elif language == 'EN':
			time_c = en_time
			
		age=self.getAge()
		str = ''
		for i in range(6):
			if age[i] == 1:
				str += "%d %s, " % (age[i],time_c[i][0])
			elif age[i] > 1:
				str += "%d %s, " % (age[i],time_c[i][1])
		return str[:-2]

if __name__=="__main__":
	
	sys.path.append("/usr/lib/zope/lib/python/DateTime")
	from DateTime import *
	
	age=Age(DateTime(2004, 7, 4), 2)
	print age.format('fr')
	age.changePrecision(4)
	print age.format('FR')
	age.changePrecision(0)
	print age.format('en')
	print "%s" % age.getFirst()

