
import calendar
from datetime import date

import iCal

from nevow import rend
from nevow.url import root
from nevow import tags as T
from nevow import formless
from nevow import freeform

class IEventsAddable(formless.TypedInterface):
    def addEvent(self, description=formless.Text()):
        """Add Event
        
        Add an event with the given description to this day.
        """
        pass
    addEvent = formless.autocallable(addEvent)


class DayDetail(rend.Page):
    __implements__ = IEventsAddable, rend.Page.__implements__

    def __init__(self, calendarEntries, year, month, date):
        self.calendarEntries = calendarEntries
        self.year = year
        self.month = month
        self.date = date
        super(DayDetail, self).__init__()

    def render_date(self, context, data):
        return "%s %s, %s" % (calendar.month_name[self.month], self.date, self.year)

    def render_events(self, context, data):
        events = self.calendarEntries.eventsFor(date(self.year, self.month, self.date))
        if not events: return "No events yet."
        return T.ol[[
            T.li[str(e)]
            for e in events
        ]]

    docFactory = rend.stan(
    T.html[
        T.head[
            T.title[
                "Detail for ", render_date]],
            T.style(type="text/css")[
                T.xml("""
                    textarea {
                      height: 1in;
                      width: 3in;
                    }""")],
        T.body[
            T.a(href=root)["Back"],
            T.h1[
                "Detail for ", render_date],
            T.h2[
                "Events:"],
            render_events,
            T.p[
                freeform.renderForms()]]])

    def addEvent(self, description):
        newEvent = iCal.ICalEvent()
        newEvent.summary = description
        newEvent.startDate = date(self.year, self.month, self.date)
        self.calendarEntries.events.append(newEvent)
