#!/usr/bin/python

import re
import sys
import dbhash
import string
import time
import os
import getopt

AssertionFailed = "Assertion failed"

def usage():
    print "Usage: display [-d] [-n] [pattern]"
    print "      (sort by date or by number)"

def by_date (left, right):
    (l_count, l_date) = string.split (db[left], "-")
    (r_count, r_date) = string.split (db[right], "-")
    if l_date > r_date:
        return -1
    elif l_date < r_date:
        return 1
    else:
        return 0
    
def by_number (left, right):
    (l_count, l_date) = string.split (db[left], "-")
    (r_count, r_date) = string.split (db[right], "-")
    l_count = int(l_count)
    r_count = int(r_count)
    if l_count > r_count:
        return -1
    elif l_count < r_count:
        return 1
    else:
        return 0
    
def error(message):
    sys.stderr.write (message + "\n")
    usage()
    sys.exit (1)

sort_criterium = None
try:
    optlist, args = getopt.getopt (sys.argv[1:], "hdn",
                                   ["help", "date", "number"])
    for option, value in optlist:
        if option == "--help" or option == "-h":
            usage()
            sys.exit(0)
        elif option == "--date" or option == "-d":
            sort_criterium = by_date
        elif option == "--number" or option == "-n":
            sort_criterium = by_number
except getopt.error, reason:
    error ("Usage: " + sys.argv[0] + ": " + str(reason))
if len (args) <= 0:
    pattern = None
else:
    pattern = re.compile(args[0], re.IGNORECASE | re.LOCALE)
db = dbhash.open (os.environ['HOME'] + '/' + '.mail-addresses', 'r')
db_sorted = db.keys()
if sort_criterium:
    db_sorted.sort (sort_criterium)
for address in db_sorted:
    if (pattern == None) or pattern.search (address):
        (counter, date) = string.split (db[address], '-')
        print str(address) + ': ' + str(counter) + ' times (last time ' + \
              time.strftime ("%d %B %Y", time.localtime (float(date))) + ')' 
db.close ()



