#!/usr/local/bin/python
# coding: iso-8859-1
# Copyright © 2009 by Amos Newcombe
# 
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.

'''a class to implement Drawings in the Python Imaging Library (PIL)
'''

from Drawing import * # Drawing, Point, Line, Rectangle
from PIL import Image, ImageDraw

def DrawPoint(drwg, draw):
	ltpnPoints = [tuple(ln) for ln in drwg.llnPoints]
	draw.point(ltpnPoints, fill=drwg.dStyle.get('color', 'black'))

def DrawLine(drwg, draw):
	ltpnPoints = [tuple(ln) for ln in drwg.llnPoints]
	draw.line(ltpnPoints, fill=drwg.dStyle.get('color', 'black'))

def DrawRectangle(drwg, draw):
	ltpnBox = [tuple(ln) for ln in drwg.llnCorners]
	draw.rectangle(tuple(ltpnBox),
		outline = drwg.dStyle.get('color', 'black'),
		fill    = drwg.dStyle.get('fill' , None   ),
	)

def DrawEllipse(drwg, draw):
	ltpnBox = [tuple(ln) for ln in drwg.llnBBox]
	draw.ellipse(tuple(ltpnBox),
		outline = drwg.dStyle.get('color', 'black'),
		fill    = drwg.dStyle.get('fill' , None   ),
	)

def DrawNothing(drwg, draw):
	pass

dfDraw = {
	Point    : DrawPoint    ,
	Line     : DrawLine     ,
	Rectangle: DrawRectangle,
	Ellipse  : DrawEllipse  ,
	Circle   : DrawEllipse  ,
	CircleCP : DrawEllipse  ,
	Metadata : DrawNothing  ,
}

def DrawPIL(drwg, draw):
# 	print 'DrawPIL(%s, %s)' % (drwg.__class__.__name__, draw)
	f = dfDraw.get(drwg.__class__)               # Look for this drawing's function.
	if f:                                        # If you can find it,
		f(drwg, draw)                            # use it.
	else:                                        # Otherwise,
		for drwgT in drwg.lContents:             # loop through the contents
			DrawPIL(drwgT, draw)                 # and draw each one.

def PILImage(sMode, tpImg, sclrBkgnd, drwg):
	img = Image.new(sMode, tpImg, sclrBkgnd)
	DrawPIL(drwg, ImageDraw.Draw(img))
	return img

if __name__ == '__main__':
	
	drwg = Drawing(
		Line((10, 100), (10, 10), (100, 10)),
		Rectangle((1, 1), (299, 299), color='blue', dasharray='1,4'),
		Point((20, 20), (20, 40), (40, 20), color='#f00'),
		Ellipse((65, 30), (35, 10), color='green'),
		Circle((75, 75), 25),
		CircleCP((30, 60), (50, 75), color='#ccc')
	)
	img = PILImage('RGB', (300,300), 'white', drwg)
	img.save('DrawPIL.png')
