
import time
import calendar
calendar.setfirstweekday(calendar.SUNDAY)

from nevow import rend


class ScheduleRoot(rend.Page):
    docFactory = rend.htmlfile('Month.html')

    def data_currentMonth(self, context, data):
        curtime = time.localtime()
        year = int(context.arg('year', curtime[0]))
        month = int(context.arg('month', curtime[1]))
        return year, month, calendar.monthcalendar(year, month)

    def render_month(self, context, data):
        year, month, weeksAndDays = data

        weekPattern = context.patternGenerator('calendarWeek')
        dayPattern = context.with(weekPattern()).patternGenerator('calendarDay')

        calendarBody = []
        for week in weeksAndDays:
            currentWeek = weekPattern().clear()
            calendarBody.append(currentWeek)
            for day in week:
                currentDay = dayPattern().clear()
                if day != 0:
                    currentDay.children.append(str(day))
                currentWeek.children.append(currentDay)

        context.fillSlots('label', "%s %s" % (calendar.month_name[month], year))
        context.fillSlots('calendarBody', calendarBody)
        return context.tag

    def data_yearsAndMonths(self, context, data):
        return [[(month, year) for month in range(1, 13)]
            for year in range(2003, 2006)]

    def render_monthSelector(self, context, data):
        tag = context.tag.clear()
        tag.attributes['href'] = "?month=%s&year=%s" % data
        tag.children.append("%s %s" % (calendar.month_name[data[0]], data[1]))
        return tag


