#!-*- coding:utf-8 -*-"

import calendar

from datetime import date, timedelta, datetime

from trac.util.datefmt import utc, format_date, format_datetime
from trac.util.translation import _

weekdays = [_(u'月'), _(u'火'), _(u'水'), _(u'木'), _(u'金'), _(u'土'), _(u'日')]

def date_to_weekday(date):
    return weekdays[date.weekday()]

def num_to_weekday(num):
    return weekdays[num]

def today():
    return date.today()

def handle_current_date(req, year_key='year', month_key='month'):
    """リクエストパラメータから日付を取得する。指定が無い場合は、現在日付を返す。
    """
    yyear = req.args.get(year_key)
    ymonth = req.args.get(month_key)
    cday = date.today()
    if not (not ymonth or not yyear):
        cday = date(int(yyear), int(ymonth), 1)
    return cday

def format_utcepoch(epoch, format='%Y-%m-%d', tzinfo=None):
    dt = datetime.fromtimestamp(int(epoch), utc)
    return format_datetime(dt, format, tzinfo)
        
def is_today(year, month, day):
    today = date.today()
    return today.year == year and today.month == month and today.day == day

def is_holiday(year, month, day, holidays):
    import datetime
    date = datetime.date(year, month, day)
    if date.isoformat() in holidays:
        return True
    else:
        return False
    
def to_timestamp(datetime):
    import time
    return time.mktime(datetime.timetuple())

def to_localtime(req, date):
    return format_datetime(date, '%Y/%m/%d %H:%M:%S', req.tz)

def prev_monthtop(cday, num):
    cday = cday.replace(day=1)
    for x in range(int(num)):
        cday = cday.replace(day=1).__add__(timedelta(days= -1)).replace(day=1)
    return cday

def next_monthtop(cday, num):
    cday = cday.replace(day=1)
    for x in range(int(num)):
        cday = cday.replace(day=1).__add__(timedelta(days=32)).replace(day=1)
    return cday