#!/usr/bin/python2
# import MySQL module

import MySQLdb
import sys
import getopt
import socket


def main(argv):
    grandtotal=0
    grandtotal_current=0
    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="ncid")
    # create a cursor
    cursor = db.cursor()
   # execute SQL statement
   # cursor.execute("select  name,number,count(number) as '# calls'  from cid group by number,name  order by '# calls' DESC  limit 20;")
   # result = cursor.fetchall()


    #Top 20 callers
    #print '<div id="content"> <p></p>'
    print '<div> <p></p>'
    print '<table class="calllog">'
    print "Top 20 callers"
    searchstring='''<td> <a href="http://www.google.com/search?q=%s" target="_blank" >  %s  </a> </td> '''
    cursor.execute("select  name,number,count(number)  from cid group by number,name  order by count(number) DESC  limit 20;")
    result = cursor.fetchall()
    for row in result:
        print "	<tr>"
        #print "		<td>",row[0],"</td>"
        print  searchstring  % (row[0], row [0])
        print "		<td>",row[2],"</td>"
        #print "		<td>",row[1],"</td>"
        print  searchstring  % (row[1], row [1])
        print "	</tr>"
        #print "%40s %26s %10s" %(row[0],row[2],row[1])
    print "</table>"
    print "</div>"


    #last 20 calls
    print '<br>'
    print '<br>'
    #print '<div id="content"> <p></p>'
    print '<div>  <p></p>'
    print '<table class="calllog">'
    print "Last 20 calls"
    print '<br>'
    cursor.execute("select date,time,name,number from cid order by date(ts) DESC ,time DESC  limit 20 ;" )
    result = cursor.fetchall()
    for row in result:
        print "	<tr>"
        print "		<td>  %s  </td>" %(row[0])
        print "		<td>",row[1],"</td>"
        #print "		<td>",row[2],"</td>"
        print  searchstring  % (row[2], row [2])
        #print "		<td>",row[3],"</td>"
        print  searchstring  % (row[3], row [3])
        print "	</tr>"
#        print "%26s %26s %26s %26s " %(row[0],row[1],row[2],row[3])
    print "</table>"
    print "</div>"

if __name__ == "__main__":
    main(sys.argv[1:])
