#!/usr/bin/python
import time
import calendar
import albatross
from albatross import SimpleApp
from albatross.cgiapp import Request


class Calendar(albatross.EmptyTag):

    name = 'alx-calendar'

    def to_html(self, ctx):
        year = self.get_attrib('year')
        if year is not None:
            year = ctx.eval_expr(year)
        month = self.get_attrib('month')
        if month is not None:
            month = ctx.eval_expr(month)
        if month is None or year is None:
            now = time.localtime(time.time())
            if year is None:
                year = now[0]
            if month is None:
                month = now[1]
        ctx.write_content('<table>\n')
        ctx.write_content('<tr align="center"><td colspan="7">%s %s</td></tr>\n' \
                          % (calendar.month_name[month], year))
        ctx.write_content('<tr>')
        for i in range(7):
            ctx.write_content('<td>%s</td>' \
                              % calendar.day_abbr[(i + 6) % 7][:2])
        ctx.write_content('</tr>\n')
        calendar.setfirstweekday(6)
        for r in calendar.monthcalendar(year, month):
            ctx.write_content('<tr align="right">')
            for i in range(7):
                if r[i]:
                    ctx.write_content('<td>%s</td>' % r[i])
                else:
                    ctx.write_content('<td></td>')
            ctx.write_content('</tr>\n')
        ctx.write_content('</table>\n')


class CalendarPage:

    def page_display(self, ctx):
        ctx.locals.year = 2002
        ctx.run_template('cal.html')


app = SimpleApp(base_url='cal.py',
                template_path='.',
                start_page='start',
                secret='-=-secret-=-')
app.register_tagclasses(Calendar)
app.register_page('start', CalendarPage())

if __name__ == '__main__':
    app.run(Request())
