# Path: src/convertdate/utils.py
# def floor(x):
#     return int(math.floor(x))
# 
# def jwday(j):
#     '''Calculate day of week from Julian day. Consider using ``calendar.weekday``!'''
#     return math.trunc((j + 0.5)) % 7
# 
# def monthcalendarhelper(start_weekday, month_length):
#     end_weekday = start_weekday + (month_length - 1) % 7
# 
#     lpad = (start_weekday + 1) % 7
#     rpad = (5 - end_weekday % 7) % 6
# 
#     days = [None] * lpad + list(range(1, 1 + month_length)) + rpad * [None]
# 
#     return [days[i : i + 7] for i in range(0, len(days), 7)]


from calendar import isleap, monthrange
from datetime import date
from .utils import floor, jwday, monthcalendarhelper
LEAP_CYCLE_DAYS = 1461

YEAR_DAYS = 365

HAVE_30_DAYS = (4, 6, 9, 11)
HAVE_31_DAYS = (1, 3, 5, 7, 8, 10, 12)


def legal_date(year, month, day):
    '''Check if this is a legal date in the Gregorian calendar'''
    if month == 2:
        daysinmonth = 29 if isleap(year) else 28
    else:
        daysinmonth = 30 if month in HAVE_30_DAYS else 31

    if not 0 < day <= daysinmonth:
        raise ValueError("Month {} doesn't have a day {}".format(month, day))

    return True


def to_jd2(year, month, day):
    '''Gregorian to Julian Day Count for years between 1801-2099'''
    # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
    legal_date(year, month, day)

    if month <= 2:
        year = year - 1
        month = month + 12


# Path: src/convertdate/utils.py
# def floor(x):
#     return int(math.floor(x))
# 
# def jwday(j):
#     '''Calculate day of week from Julian day. Consider using ``calendar.weekday``!'''
#     return math.trunc((j + 0.5)) % 7
# 
# def monthcalendarhelper(start_weekday, month_length):
#     end_weekday = start_weekday + (month_length - 1) % 7
# 
#     lpad = (start_weekday + 1) % 7
#     rpad = (5 - end_weekday % 7) % 6
# 
#     days = [None] * lpad + list(range(1, 1 + month_length)) + rpad * [None]
# 
#     return [days[i : i + 7] for i in range(0, len(days), 7)]


# Path: src/convertdate/gregorian.py
from calendar import isleap, monthrange
from datetime import date
from .utils import floor, jwday, monthcalendarhelper

LEAP_CYCLE_DAYS = 1461

YEAR_DAYS = 365

HAVE_30_DAYS = (4, 6, 9, 11)
HAVE_31_DAYS = (1, 3, 5, 7, 8, 10, 12)


def legal_date(year, month, day):
    '''Check if this is a legal date in the Gregorian calendar'''
    if month == 2:
        daysinmonth = 29 if isleap(year) else 28
    else:
        daysinmonth = 30 if month in HAVE_30_DAYS else 31

    if not 0 < day <= daysinmonth:
        raise ValueError("Month {} doesn't have a day {}".format(month, day))

    return True


def to_jd2(year, month, day):
    '''Gregorian to Julian Day Count for years between 1801-2099'''
    # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
    legal_date(year, month, day)

    if month <= 2:
        year = year - 1
        month = month + 12


    a = floor(year / 100)