"""
Blog macro 0.1-alpha
Usage sample 1: [[Blog(blog/%)]]
Usage sample 2: [[Blog(2004%,blog/%)]]

"""

from StringIO import StringIO
import re,time
import string
#from trac.WikiFormatter import *
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("args.page", "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()
    #formatter = Formatter(hdf, env, db, 0)
    
    years = {}
    # years = {
    #    2004: {
    #       1: 1,
    #       2: 3,
    #    },
    #    2005: {
    #       2: 4,
    #       3: 3,
    #    },
    # }
    
    out1 = StringIO()   # the TOC
    #~ out1.write('<p>Blog of %d/%d</p>' % (year, month))
    out1.write('<a name="toc"></a><ul>')
    
    out2 = StringIO()   # the body
    bIndex = 0
    
    for blogPattern in args.split(','):
        blogPattern = blogPattern.strip()
        sql = "SELECT DISTINCT name from wiki where name like '%s' order by time desc" % 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
                    
                text = rowText[0]
                timeStr = time.ctime(rowText[1])
                author = rowText[2]
                out3 = StringIO()   # the rendered output of current wiki
                #~ env.log.debug('rendering %s' % pagename)
                #formatter.format(text, out3)
                out3.write(wiki_to_html(text,env,hdf,db,0))
                text = out3.getvalue()
                out3 = None
                
                # 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
                out1.write('<li><a name="t%d"></a><a href="#b%d">%s</a></li>' % (bIndex, bIndex, title))
                
                out2.write('<a name="b%d"></a>' % bIndex)
                out2.write('<div class="nav"><ul>')
                out2.write('<li><a href="%s">%s</a></li>' % (env.href.wiki(name), title))
                out2.write('<li>%s</li>' % author)
                out2.write('<li>%s</li>' % timeStr)
                out2.write('<li><a href="#t%d">top</a></li>'  % bIndex)
                out2.write('</ul></div>')
                
                
                out2.write(text)
    out1.write('</ul>')
    
    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(out1.getvalue())
    out.write(out2.getvalue())
    return out.getvalue()

