########################################################################
#
# File Name: 		DateFactory.py
#
# Documentation:	http://docs.ftsuite.com/4ODS/DateFactory.py.html
#
"""
Implements the DateFactory interface.
WWW: http://4suite.org/4ODS         e-mail: support@4suite.org

Copyright (c) 1999-2001 Fourthought Inc, USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""
#"

from Ft.Ods import Date, Exception



InvalidDate = Exception.InvalidDate


def julian_date(year,julian_day):

    month = 0
    dayCtr = julian_day
    while dayCtr > days_in_month(year,Date.Date.Month.elements[month]):
        dayCtr = dayCtr - days_in_month(year,Date.Date.Month.elements[month])
        month = month + 1
        if month == 13:
            month = 1
            year = year + 1

    return Date.Date(None,(year,month+1,dayCtr))



def calendar_date(year,month,day):
    return Date.Date(None,(year,month,day))


def is_leap_year(year):
    if not year % 400:
        if not year % 100: return 0
        return 1
    if not year % 4: return 1
    return 0


def is_valid_date(year,month,day):
    if month < 1 or month > 12:
        return 0
    if day < 1 or day > days_in_month(year,month):
        return 0
    return 1

def days_in_year(year):
    return is_leap_year(year) and 366 or 365

def days_in_month(year,month):
    if month == Date.Date.Month.February and is_leap_year(year):
        return 29
    elif month == Date.Date.Month.February:
        return 28
    elif month in [Date.Date.Month.January,
                   Date.Date.Month.March,
                   Date.Date.Month.May,
                   Date.Date.Month.July,
                   Date.Date.Month.August,
                   Date.Date.Month.October,
                   Date.Date.Month.December]:
        return 31
    return 30


