# To use this macro, place in a page which is under a calendar:
#   <<CalDate("%d %B %Y")>>
# If it's under a calendar which has the date "2004-10-28",
# it will render as "28 October, 2004".  It also allows you
# to use:
#   <<CalDate("%d %B %Y",7)>>
# This will advance the output by 7 days.  So you get
# "4 November, 2004".  I use this on my chorus rehearsal
# notes page where I want to have a section describing the
# last rehearsal, and then a section describing the upcoming
# rehearsal.
#
# Gary Godfrey
# Austin, TX USA
# 11 April, 2008
# ggodfrey+caldate@io.com
# Version 0.1

import datetime
import re
Dependencies = []
# Look for:
#   "anything in quotes"
#   "anything in quotes",5
fmtre = re.compile(r'^"([^"]+)"(?:|,\s*(-*\d+))$')
fmtdt = re.compile(r'^(\d+)-(\d+)-(\d+)')

def execute(macro, args):
    # Args: (fmt,[days offset])
    #       Fmt is a date/time format (see strftime(3))
    #       Days offset is the number of days to offset the calendar day.
    args = args.encode()        # Make string instead of unicode
    try:
        (datefmt,dayOffset) = fmtre.match(args).groups()
    except:
        return "Badly formatted CalDate options"

    # Get the url from the request object.  Parse the date and alter
    # the date based on the args
    req = macro.request
    try:
	datetext = req.getPathinfo().split('/')[-1]
	(year, month, day) = fmtdt.match(datetext).groups()
        caldate = datetime.date(int(year),int(month),int(day))
    except:
	return "Can't figure out date from url.  Is this under a calendar?"

    if dayOffset:
        caldate = caldate + datetime.timedelta(days=int(dayOffset))

    str = caldate.strftime(datefmt)
    try:
        str = caldate.strftime(datefmt)
    except:
        str = "Badly Formated Date"

    return str

if __name__ == '__main__':
    class tst:
	def __init__(self):
	    self.request = self
	def getPathinfo(self):
	    return 'calendarpath/2008-04-24'

    t = tst()
    assert execute(t,'"%d %B, %Y"') == '24 April, 2008'
    assert execute(t,'"%d %B, %Y",2') == '26 April, 2008'
    print "Test done"
