
import time
from datetime import date
import calendar
calendar.setfirstweekday(calendar.SUNDAY)

from nevow import tags as T
from nevow import rend
from nevow.url import here, root


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

    def __init__(self, calendarEntries):
        self.calendarEntries = calendarEntries
        super(ScheduleRoot, self).__init__()

    def data_currentMonth(self, context, data):
        curtime = time.localtime()
        year, month = curtime[0], 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')
        curtime = time.localtime()
        curYear, curMonth, curDate = curtime[0], curtime[1], curtime[2]

        calendarBody = []
        for week in weeksAndDays:
            currentWeek = weekPattern().clear()
            calendarBody.append(currentWeek)
            for day in week:
                if day != 0:
                    events = self.calendarEntries.eventsFor(date(year, month, day))
                else:
                    events = []
                today = None
                if curYear == year and curMonth == month and curDate == day:
                    today = 'today'
                currentDay = dayPattern(
                    id=today,
                    render=self.render_day,
                    data=(year, month, day, events)
                )
                currentWeek.children.append(currentDay)

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

    def render_day(self, context, data):
        year, month, day, events = data
        if day == 0:
            day = ''
            eventsDOM = ''
        else:
            url = here.child(str(year)).child(str(month)).child(str(day))
            eventsDOM = context.onePattern('events').clear()
            numEvents = len(events)
            eventsDOM(href=url, _class=numEvents == 0 and "add-events" or "edit-events")
            if events:
                eventText = "%s event%s" % (numEvents, numEvents > 1 and 's' or '')
            else:
                eventText = "Add event"
            eventsDOM.children.append(eventText)

        context.fillSlots('date', day)
        context.fillSlots('events', eventsDOM)
        return context.tag

    def locateChild(self, request, childSegments):
        if childSegments == ('',):
            ## We are looking for the root of the site, aka /
            return self, ()
        try:
            year, month, date = map(int, childSegments[:3])
            import day
            return day.DayDetail(self.calendarEntries, year, month, date), childSegments[3:]
        except ValueError:
            # If the url doesn't consist of a tuple of year, month, day, or the segments
            # are not integers, then we render a 404 page.
            return rend.NotFound

