#!/usr/bin/env python

import re,csv
from email.utils import parsedate
from time import mktime
from datetime import datetime
from os import popen
from sys import argv,stderr,stdout

needsvg=len(argv)>1 and argv[1]=='--svg'
needsNet=len(argv)>1 and argv[1]=='--net'

fc=0
locs=0
adds=None
dels=None
cmt=None
d=None

maxAdds=0
maxDels=0
maxLocs=0

h=[]

def pop():
	global locs,dels,adds,cmt,h,d,maxAdds,maxDels,maxLocs
	if adds is not None:
		if adds > maxAdds:
			maxAdds = adds
		if dels > maxDels:
			maxDels = dels
		if locs > maxLocs:
			maxLocs = locs
		
		pstr="%s %8u %5s %5s %7s %s \t\t%s"%(d,locs,'+'+str(adds),'-'+str(dels),hsh,who,cmt.strip())
		if needsvg or needsNet:
			stderr.write(pstr+'\n')
		else:
			print(pstr)
		h.append((d,locs,adds,dels,hsh,who,cmt))

for x in popen('git log --reverse -p'):
	if x.startswith('commit'):
		pop()
		hsh=x[7:14];
	if x.startswith('Author'):
		who=x.replace("Author: ",'').replace('\n','');
		who=re.sub(">.*","",who);
		who=re.sub(".*<","",who);
		who,stuff = who.split("@")
	if x.startswith('Date'):
		fc=1
		d=datetime(*parsedate(x[5:])[:7])
		t=mktime(parsedate(x[5:]))
		adds=0
		dels=0
	if fc==2:
		cmt=x[:-1]
		fc=0
	if fc==1:
		if len(x)==1: fc=2
	if x.startswith('+') and not x.startswith('+++'):
		adds+=1
		locs+=1
	if x.startswith('-') and not x.startswith('---'):
		dels+=1
		locs-=1

pop()

def quoteone(x):
	if x in 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789': return x
	return "&#x%02x;"%(ord(x),)

def quote(s):
	return ''.join([quoteone(x) for x in s])

def makesvg():
	global locs,dels,adds,cmt,h,d,maxAdds,maxDels,maxLocs
	
	
	mlocs=int(max([maxAdds,maxDels,maxLocs]) * 1.1)
	stderr.write(str(mlocs)+'\n')
	yscale=1920.0/mlocs

	svg=stdout
	svg.write("""<?xml version="1.0" standalone="no"?>"""
		  """<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">"""
		  """<svg preserveAspectRatio="none"  viewBox="0 0 %u %u" version="1.1" xmlns="http://www.w3.org/2000/svg">"""%(25*len(h),mlocs*yscale))

	svg.write("""<style>"""
		  """rect.o{opacity:0}"""
		  """rect.o:hover{opacity:0.2}"""
		  """.a{fill:none;stroke:black;stroke-width:2}"""
		  """</style>""")

	def rect(x,y,w,h,c,a=''):
		svg.write("""<rect x="%u" y="%u" width="%u" height="%u" style="%s" %s/>"""
				%(x,y,w,h,c,a))


	ps=[]
	bl=[]
	tx=[]
	x=25
	hsh=None
	who=None
	for d,locs,adds,dels,hsh,who,cmt in h:
		y=(mlocs-locs)*yscale
		bl.append((x-1,y,3,dels*yscale,"fill:rgb(0,0,255)"))
		bl.append((x-1,y-adds*yscale,3,adds*yscale,"fill:rgb(0,255,0)"))

		bl.append((x-12,0,25,mlocs*yscale,'',
			"""title="%s %8u %5s %5s   %s" """%(d,locs,'+'+str(adds),'-'+str(dels),quote(cmt.strip()))
			+"""class="o" """))

		ps.append("%u,%u"%(x,y))
		x+=25

	svg.write("""\n""")
	svg.write("""<polyline points="0,%u %u,%u" class="a"/>"""%(mlocs*yscale,x,mlocs*yscale,))
	svg.write("""<polyline points="25,0 25,%u" class="a"/>"""%(mlocs*yscale+25,))

	it=pow(10,len(str(mlocs))-2)
	for i in range(it,mlocs,it):
		svg.write("""<polyline points="0,%u %u,%u" class="a" style="stroke:rgb(200,200,200)"/>"""%(mlocs*yscale-i*yscale,x,mlocs*yscale-i*yscale,))
		svg.write("""\n""")

	for b in bl:
		rect(*b)
		svg.write("""\n""")

	svg.write("""<polyline points="%s" class="a" style="stroke:red"/>"""%(' '.join(ps),))


		

	svg.write("""</svg>\n""")

def makenet():
	global h
	
	d=None
	locs=None
	adds=None
	dels=None
	hsh=None
	who=None
	cmt=None
	table = dict()
	for d,locs,adds,dels,hsh,who,cmt in h:
		if not table.has_key(who):
			table[who]=[0,0,0,0]
		cur = table[who]
		cur[0] += adds
		cur[1] += dels
		cur[2] += adds - dels
	
	html=True
	if html:
		print "<html><table>"
		for k,v in table.iteritems():
			sv = map(str,v)
			print "<tr><td>"+str(k)+"</td><td>"+"</td><td>".join(sv)+"</td></tr>"
		print "</table></html>"
	else:
		#oWriter = csv.writer(oFile)
		print "Not Ready"

if needsvg: makesvg()
if needsNet: makenet()
