from TAL.DummyEngine import DummyEngine
from TAL.driver import compilefile
from TAL.TALInterpreter import TALInterpreter
from WebKit.Page import Page
from cStringIO import StringIO

class WebKitEngine(DummyEngine):
	"""  
	Override DummyEngine's __init__ to take the WebKit page object to which we wish to refer in our
	TAL Template HTML. Call DummyEngine.__init__ to initialize the engine, then add
	page to the local namespace.
	"""
	def __init__(self, page):
		DummyEngine.__init__(self)
		
		# Add page to the WebKitEngine's local namespace so that the variable 'page' will be accessible
		# from TAL.
		self.setLocal('page', page)

class TALPage(Page):
	"""
	TALPage makes TAL do the work of generating the HTML from a template file
	"""
	base = ''
	file = ''

	def writeHTML(self):
		assert self.base + self.file, "self.base + self.file should point to the TAL file you wish to process"

		# Create a memory-mapped file for TALInterpreter to write the final HTML output to.
		fileObj = StringIO()

		# Compilefile returns a two-element tuple containing the program and the macros to interpret

		program, macros = compilefile(self.base + self.file, "html")

		# Create a WebKitEngine and pass it a reference to ourself (The current page object)
		engine = WebKitEngine(self)
		TALInterpreter(program, macros, engine, fileObj, wrap=0, tal=1, showtal=-1, strictinsert=1)()

		# Now send the page to WebKit for output to the web browser.
		self.writeln(fileObj.getvalue())
		fileObj.close()
