#!/usr/local/bin/python
import sys, traceback, html
from assert import assert, TRUE, FALSE
from Para import Para
from Line import Line

class Outline:
	def __init__(self, filename):
		'''initialize Outline from filename
		
		Track line numbers for each line,
		and create new paragraphs, adding them to self.root.
		
		Each line starts a new paragraph, except
		that lines ending with '\' are continued,
		and lines beginning with '[' continue until
		a line ending with an unescaped ']'
		'''
		self.filename = filename
		self.paras = Para(-1, None, [])

		saved = []
		position = 0	# line number
		fp = open(filename)
		while TRUE:
			line = fp.readline()
			position = position + 1
			if not line:
				break
			lastLine = Line(filename, line, position)
			
			# ignore comment or empty lines
			if lastLine.isComment() or lastLine.isEmpty():
				continue

			saved.append(lastLine)
			
			# Send the list of lines to the root paragraph,
			# which returns true if this is a full paragraph.
			if self.paras.addLines(saved):
				saved = []
			# check to see if we've completed a paragraph
		fp.close()
		
		# It's bad if there are any leftover lines
		if saved:
			for line in saved:
				line.warn("incomplete paragraph")

	def renderHTML(self, template=None):
		'''Return HTML rendering, using optional template
		
		If template is used, it should be a string containing
		formatting operators "%(body)s" and "%(title)s"
		'''
		body = self.paras.render('HTML')
		if template:
			title = self.paras.getTitle()
			return template % locals()
		else:
			return body

def usage():
	sys.stderr.write("outline.py [-p printfile ] [-t template] file [file ...]")

def main():
	'''outline.py [-t template] file [file ...]
	'''
	import getopt
	opts, args = getopt.getopt(sys.argv[1:], 'p:t:')
	template = html.DEFAULT_TEMPLATE
	printout = ''
	for switch, val in opts:
		if switch == '-t':
			template = open(val).read()
		elif switch == '-p':
			printout = open(val, 'w')
		else:
			usage()
	verbose = TRUE
	whine = sys.stderr.write
	for file in args:
		if verbose:
			whine("%s: reading ... " % (file,))
		o = Outline(file)
		if verbose:
			whine("rendering ... ")
		rendered = o.renderHTML(template)
		
		if printout:
			printout.write(rendered)
		else:
			outfile = file+'.html'
			out = open(outfile, 'w')
			out.write(rendered)
			out.close()
			if verbose:
				whine("done %s \n" % outfile)
	if printout:
		printout.close()

if __name__ == '__main__':
	main()
