"""
    MoinMoin - MonthCalendar Top List MACRO
                
                Original Author : Mark Stier
                Mantained by Eric Veiras Galisson
                
                May be used to create a Blog off of a MonthCalendar data structure.
                 
                Based on:
                    MonthCalendar macro from MoinMoin 1.5.2

    Call this macro on a base page for a MonthCalendar.
                It will pack the contents of all tips you get when moving a mouse
                over some day entry into a simple, clickable list.

    This is an addition to the MonthCalendar macro, so you should make
                yourself familiar with THAT one before trying to understand what this action
          can do for you.
"""

Dependencies = ['namespace','time']

import re, calendar, time, StringIO, os
from datetime import date, timedelta
from MoinMoin import config, wikiutil, util
from MoinMoin.Page import Page

def execute(macro, text):
        request = macro.request
        formatter = macro.formatter
        thispage = formatter.page.page_name

        max_days = 365
        n_max_def = 10
        if text is not None:
                try:
                        n_max = int(text) # max entries to display
                except ValueError:
                        n_max = n_max_def
        else:
                n_max = n_max_def
        now = date.today()

    	raw_str = r"""
        	^\s*		# line start

        	(	
                '''\s*(.*)\s*'''
       	    |
                =\s+(.*)\s+=
            )

            \s*$        # end of line
            """		

	compile_obj = re.compile(raw_str, re.MULTILINE|re.VERBOSE)

        result = []
        n_cnt = 0
        for i in range(-1,n_max): # include next day because of different timezones
            dte = now - timedelta(i)
            datestr = "%4d-%02d-%02d" % (dte.year, dte.month, dte.day)
            link = "%s/%s" % (thispage, datestr)
            daypage = Page(request, link)
            if daypage.exists() and request.user.may.read(daypage.page_name):
                daycontent = daypage.get_raw_body()

		m = compile_obj.search(daycontent)			

	    	if m:
		    if m.group(2) == None:
		    	x = m.group(3)
		    else:
		    	x = m.group(2)
		    result.append("<a href=\"%s/%s\">%s (%s)</a>" % (request.getBaseURL(),link,x,datestr))
		else:
		    result.append("<a href=\"%s/%s\">%s (%s)</a>" % (request.getBaseURL(),link,"Untitled",datestr))
            if n_cnt == n_max:
                break
                
        if len(result) == 0:
                result = ["Sorry, there are no entries within the last %d days." % n_max]
        return formatter.rawHTML('<br>'.join(result))
