#!/usr/bin/python
#
# Copyright © 2011 David Bremner <david@tethera.net>
# License: Same as notmuch

import datetime
import notmuch
import sys

QUERY = "tag:notmuch::patch and not tag:notmuch::pushed"
QUERY += "  and not tag:notmuch::obsolete and not tag:notmuch::wip"
QUERY += " and not tag:notmuch::stale and not tag:notmuch::contrib"
QUERY += " and not tag:notmuch::python and not tag:notmuch::vim"
QUERY += " and not tag:notmuch::moreinfo"

def html_row(*args):
    print '  <tr><td>'
    print '    </td><td>'.join(args).encode('utf-8')
    print '  </td></tr>'

db = notmuch.Database(mode=notmuch.Database.MODE.READ_WRITE)
q_new = notmuch.Query(db, QUERY)
q_new.set_sort(notmuch.Query.SORT.OLDEST_FIRST)

headers = ['date','from','subject']
last = {}

for header in headers:
    last[header] = None

print '<h2>Notmuch Patches</h2>'

print 'Generated: %s<br>' % datetime.date.today()

print 'For more information see <a href="https://notmuchmail.org/nmbug">nmbug</a>'

print '<h3>Query</h3>'
print QUERY

print '<h3>Result</h3>'


print '<table>'
for m in q_new.search_messages():

    out = {};

    for header in headers:
	if header != 'date':
	    val = m.get_header(header)
	else:
	    val = datetime.date.fromtimestamp(m.get_date()).isoformat()

	if last[header] == val:
	    out[header] = ""
	else:
	    out[header] = val
	    last[header] = val

    mid=m.get_message_id()

    out['id'] = '<a href=http://mid.gmane.org/%s>id:%s</a>' % (mid,mid)

    html_row(out['date'],out['from'],out['subject'],out['id'])

#    print '%(date)-10.10s %(from)-20.20s %(subject)-40.40s id:%(id)s' %  out
print '</table>'