"""
Blog macro 0.2-alpha [[BR]]
Usage sample 1: {{{[[Blog(blog/%)]]}}} [[BR]]
Usage sample 2: {{{[[Blog(2004%,blog/%)]]}}} [[BR]]

"""

from StringIO import StringIO
import re,time
import string
from trac.wiki import wiki_to_html

month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def execute(hdf, args, env):
    if hdf.getValue( 'macro.blog.rendering', '0' ) == '1':
        return ""
    hdf.setValue( 'macro.blog.rendering', '1' )

    pagename = hdf.getValue( 'wiki.page_name', 'WikiStart' )

    # we can accept two optional parameters: year and month, if not provided, will use today's
    timeToday = time.localtime()
    year      = int( hdf.getValue( "args.year",  str( timeToday.tm_year ) ) )
    month     = int( hdf.getValue( "args.month", str( timeToday.tm_mon  ) ) )

    db = env.get_db_cnx()

    years = {}
    # years = {
    #    2004: {
    #       1: 1,
    #       2: 3,
    #    },
    #    2005: {
    #       2: 4,
    #       3: 3,
    #    },
    # }

    toc  = []  # the TOC
    body = []  # the body
    bIndex = 0

    toc.append( '</ul>' )  # remember: TOC and body are reversed before joining

    for blogPattern in args.split( ',' ):
        blogPattern = blogPattern.strip()
        sql = "SELECT DISTINCT name from wiki where name like '%s' order by time" % blogPattern
        csName = db.cursor()   # the matched wiki name
        csName.execute( sql )
        while 1:
            rowName = csName.fetchone()
            if rowName == None:
                break

            name = rowName[0]

            sql = "SELECT text,time,author from wiki where name = '%s' order by version desc limit 1" % name
            csText = db.cursor()    # the wiki text and time and author
            csText.execute( sql )
            while 1:
                rowText = csText.fetchone()
                if rowText == None:
                    break

                timeParts = time.localtime(rowText[1])
                if not timeParts.tm_year in years.keys():
                    years[timeParts.tm_year] = {timeParts.tm_mon: 1}
                else:
                    if not timeParts.tm_mon in years[timeParts.tm_year].keys():
                        years[timeParts.tm_year][timeParts.tm_mon] = 1
                    else:
                        years[timeParts.tm_year][timeParts.tm_mon] += 1
                    
                if timeParts.tm_year != year or timeParts.tm_mon != month:
                    break

                #~ env.log.debug( 'rendering %s' % pagename )
                text    = wiki_to_html( rowText[0], env, None, db, 0 )
                timeStr = time.ctime(rowText[1])
                author  = rowText[2]

                # get the wiki title from its output
                matchedTitle = re.search( r"<(h\d+).*?>(.*?)</\1>", text )
                title = name
                if matchedTitle != None:
                    title = string.strip( matchedTitle.group(2) )

                bIndex+=1
                toc.append( '<li><a name="t%d"></a><a href="#b%d">%s</a></li>' 
                                % (bIndex, bIndex, title) )

                body.append( text )
                body.append( '<a name="b%d"></a>'
                             '<div class="nav">'
                               '<ul>'
                                 '<li><a href="%s">%s</a></li>'
                                 '<li>%s</li>'
                                 '<li>%s</li>'
                                 '<li><a href="#t%d">top</a></li>'
                               '</ul>'
                             '</div>' 
                             % (bIndex, env.href.wiki(name), title, author, timeStr, bIndex) )

    toc.append( '<a name="toc"></a><ul>' )
    #~ toc.append( '<p>Blog of %d/%d</p>' % (year, month) )

    # Reverse TOC and body to put the most recent items at the top
    toc.reverse()
    body.reverse()

    out = StringIO()
    #~ out.write( '<p>Blog by Date:</p>' )
    out.write('<ul>')
    ykeys = years.keys()
    ykeys.sort()
    ykeys.reverse()
    for y in ykeys:
        out.write( '<li>%d:' % y )
        for m in years[y].keys():
            if y == year and m == month:
                out.write( '&nbsp;%s(%d)' % (month_abbr[m-1], years[y][m]) )
            else:
                shref = '<a href="%s?year=%d&month=%d">' % (env.href.wiki(pagename), y, m)
                out.write( '&nbsp;%s%s</a>(%s%d</a>)' % (shref, month_abbr[m-1], shref, years[y][m]) )
        out.write( '</li>' )
    out.write( '</ul>' )
    out.write( ''.join(toc) )
    toc = None
    out.write( ''.join(body) )
    body = None
    return out.getvalue()


