"""
    MoinMoin - MonthCalendarTopList Macro
    
    You can use this macro to generate a list of recent entries from 
     a MonthCalendar data structure.
    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.          

    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.


     @copyright: ?-2006 Mark Stier
     @copyright: 2007 Eric Veiras Galisson 
     @license: GNU GPL v2 - see http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt for details. 
                    
    Revisions:
    * unnumbered: original version by Mark Stier. 
    
    * 1.0
      * modification to make it work with MoinMoin 1.5
    * 1.1
      * added support of titles in the form:
        * = title =
        or
        * '''title'''
      * if no title exists, the page still appears in the list named Untitled
      * only the first title appears
    * 1.2
      * back to the previous behaviour allowing several titles
    
    
    Usage:
      [[MonthCalendarTopList(X)]]
      
      will display the last X days entries.
"""

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)
	    print daypage
            if daypage.exists() and request.user.may.read(daypage.page_name):
                daycontent = daypage.get_raw_body()

		pattern = compile_obj
		for match in pattern.finditer(daycontent):
			if match:
				if match.group(2) == None:
					title = match.group(3)
				else:
					title = match.group(2)
				result.append("<a href=\"%s/%s\">%s (%s)</a>" % (request.getBaseURL(),link,title,datestr))
			else:
				result.append("<a href=\"%s/%s\">%s (%s)</a>" % (request.getBaseURL(),link,"pas de titre",datestr))
                
        if len(result) == 0:
                result = ["Sorry, there are no entries within the last %d days." % n_max]
        return formatter.rawHTML('<br>'.join(result))
