#


# http://www.pythonware.com/library/pil/handbook/

import sys
import Colors
import Image, ImageDraw, ImageFont

Color = Colors.Colors()

class BarChartImage:

	diff_top = 16
	height = 12
	top = offset_top = 60
	offset_left = 80
	offset_right = 30
	shadow_color = Color.DarkGrey
	shadow_color = Color.grey
	bars = []

	def __init__(self, title="Scores", filename="cycle.png", fontname="tahoma.ttf"):
		self.font = ImageFont.truetype(fontname, self.height-6)
		self.fontname = fontname 
		self.title = title
		
		labelfontsize = int(round(self.height*.8,0))
		self.labelfont = ImageFont.truetype(fontname, labelfontsize)
		
		self.image = Image.open(filename)
		self.bars = {}
		self.bar_order = []
		self.subtitle = ""
		self.enable_shadow = True

	def drawTitle(self, title, color=Color.black):
		titlefontsize = int(round(self.height*1.5,0))
		titlefont = ImageFont.truetype(self.fontname, titlefontsize)
		if self.enable_shadow:
			self.draw.text((20+2,2+2), title, font=titlefont, fill=self.shadow_color)
		self.draw.text((20,2), title, font=titlefont, fill="#000000")
		
		subtitlefontsize = int(round(self.height,0))
		subtitlefont = ImageFont.truetype(self.fontname, subtitlefontsize)
		if self.enable_shadow:
			self.draw.text((40+1,35+1), self.subtitle, font=subtitlefont, fill=self.shadow_color)
		self.draw.text((40,35), self.subtitle, font=subtitlefont, fill="#000000")

	def addBar(self,name,perc,color=Color.black,label=None):
		if name in self.bars.keys():
			self.bars[name].append((perc,color,label))
		else:
			self.bars[name] = []
			self.bars[name].append((perc,color,label))
			
	def subTitle(self, subtitle):
		self.subtitle = subtitle

	def drawImage(self,out_name):
		self.prepareImage()
		for name in self.bar_order:
			self.drawBars(self.bars[name],name)
			self.offset_top = self.offset_top + self.diff_top

		self.image.save(out_name)
		print "Saved image ", out_name
		print "-----------------------"
		del self.draw
		self.bars = []
	
	def prepareImage(self):
		#print "Image: ", self.image.size
		#print len(self.bars), "authors"
		image_height = self.top*2 + (len(self.bars) * (self.diff_top))
		self.image = self.image.resize((400, image_height))

		self.draw = ImageDraw.Draw(self.image)

		self.drawTitle(self.title)
		# Make legend.
		#print "Image: ", self.image.size
		position_a = (20, self.image.size[1]-55)
		position_b = (30, self.image.size[1]-40)
		position_c = (30, self.image.size[1]-25)
		self.draw.text(position_a, "Legend:", 
															font=self.labelfont, fill=Color.black)
		self.draw.text(position_b, "bars: percentage of total commits (number)", 		
															font=self.labelfont, fill=Color.black)
		#self.draw.text(position_c, "balk: percentage totaal aantal commits (percentage met commentaar)", 
															#font=self.labelfont, fill=Color.black)
		#print "A: ", position_a
		#print "B: ", position_b
		#print "C: ", position_c
		
		# Draw bounding box around bars
		linecolor = Color.grey
		top = self.top-self.height/2
		#bottom = self.offset_bottom+self.height/2
		bottom = self.offset_top+((self.diff_top)*(len(self.bars)))
		coords = [(self.offset_left,self.top-self.height/2),(self.image.size[0]-self.offset_right,bottom)]
		self.draw.rectangle(coords ,outline=linecolor)
		
		# Draw lines at 25, 50, 75%
		
		for v in (0.25,0.5,0.75):
			cy = self.offset_left + ((self.image.size[0] - self.offset_right - self.offset_left) * v)
			self.draw.line((cy,top,cy,bottom), fill=linecolor)

	def drawBars(self,bars,name):
		cx = self.offset_left # offset from left
		cy = self.offset_top # offset from top
		#print "Length:",name, length, perc
		tl = (cx, cy)
		tr = (cx, cy+self.height)

		shadow_offset = 2
		# Draw shadow
		if self.enable_shadow:
			self.draw.text((10+1,self.offset_top+1), name, font=self.labelfont, fill=self.shadow_color)
		
		# We've already drawn a shadow, only do this for the lowest layer
		has_label = has_shadow = False 
		label = ""
		i = 0
		for bar in bars:
			perc,color,new_label = bar
			length = float(self.image.size[0]-cx-self.offset_right) * perc * 4
			bl = (cx+length, cy)
			br = (cx+length, cy+self.height)
			if self.enable_shadow and not has_shadow:
				self.draw.rectangle([(tl[0]+shadow_offset,tl[1]+shadow_offset),
						(br[0]+shadow_offset,br[1]+shadow_offset)], fill=self.shadow_color)
				has_shadow = True
			if new_label:
				label += str(new_label)
			if not has_label:
				perc_label = (str(round((perc*100),1))) + "%"
				self.draw.text((tl[0]+length+5,self.offset_top+4),perc_label,font=self.labelfont,fill=Color.black)
				has_label = True
				if label:
					label = "("+str(label)+")"
					self.draw.text((tl[0]+length+self.labelfont.getsize(perc_label)[0]+10,self.offset_top+4),
						label,font=self.labelfont,fill=Color.black)

			self.draw.rectangle([tl,br], fill=color)
			i = i+1
		self.offset_bottom = tr[1]
		self.draw.text((10,self.offset_top), name, font=self.labelfont, fill=Color.black)


if __name__ == "__main__":
	bar = BarChartImage("Moron-Meter")
	bar.subTitle("These people are idiots")

	bar.addBar("Kurt", .38, Color.DarkOrange, "n00b")
	bar.addBar("Thomas", .457, Color.orangered, "aap")
	bar.addBar("Luke", .71, Color.DarkGreen, "crazy fuck")
	bar.addBar("Luke", .41, Color.seagreen)
	
	bar.addBar("Snurgo", .5133, Color.DarkBlue, "mongool")
	bar.addBar("Snurgo", .21, Color.SlateBlue1)

	bar.drawImage("test.png")

