#!/usr/bin/python

import sys
import os
from aa_macro import *

report = False
suppress = False
nocolor = False
genoutput = True

try:
	from aa_ansiicolor import *
except:
	ac = None
else:
	ac = htmlAnsii()

def lx(s,color):
	global ac
	global nocolor
	if ac != None:
		if nocolor == False:
			s = ac.c(s,color)
	return s

argv = sys.argv[1:]

def optr(oa,ob,p,c):
	flgcolor = 'purple' # flag color
	optcolor = 'white'	# option color
	parcolor = 'green'	# parenthesis color
	prmcolor = 'yellow'	# parameter color
	barcolor = 'white'	# 'or' bar color
	comcolor = 'green'	# comment color
	s = ''
	s += 4 * ' '
	pm = p
	if pm != '': pm = ' ' + pm
	if p != '': p = ' ' + lx(p,prmcolor)
	l = len('%s %s%s%s%s%s' % ('(','-'+oa,'|','--'+ob,pm,')'))
	pad = (28 - l) * ' '
	x = '%s %s%s%s%s%s%s' % (lx('(',parcolor),lx('-'+oa,flgcolor),lx('|',barcolor),lx('--'+ob,flgcolor),p,lx(')',parcolor),pad)
	s += '%s %s' % (x,lx(c,comcolor))
	print s

def usage():
	print "Usage"
	print "-------------------------------------------------------------------------------"
	print "aagen inputFileName"
	optr('f','file','outputFileName','Write output to file')
	optr('r','report','','Report input and output text lengths')
	optr('s','suppress','','Suppress stdout usage printout when error')
	optr('nc','ncolor','','Don\'t use console color (color requires aa_ansiicolor)')
	optr('ng','nogen','','Don\'t generate output')
	optr('o','open','','Send output to OS X HTML browser')
	optr('i','include','includeFileName','Process this file first')
	print "-------------------------------------------------------------------------------"

def error(msg):
	global c
	global suppress
	if suppress != True:
		usage()
	sys.stderr.write(lx('ERROR: ','red') + lx(msg,'yellow')+'\n')
	raise SystemExit

def idarg(arg,match):
	alen = len(match)
	if arg[:alen] == match:
		return True
	return False

ofn = ''
ifn = ''
mfn = ''
off = False
mff = False
mmff = False
gfn = False
osx = False
noparms = True
for arg in argv:
	if off == True:
		ofn = arg
		off = False
		if arg != '':
			gfn = True
		else:
			error('No filename specified after "--file or -f"')
	elif mff == True:
		mfn = arg
		mff = False
		if arg != '':
			mmff = True
		else:
			error('No filename specified after "--include or -i"')
	elif idarg(arg,'--file') == True or idarg(arg,'-f') == True:
		off = True
		noparms = False
	elif idarg(arg,'--open') == True or idarg(arg,'-o') == True:
		osx = True
		noparms = False
	elif idarg(arg,'--include') == True or idarg(arg,'-i') == True:
		mff = True
		noparms = False
	elif idarg(arg,'--report') == True or idarg(arg,'-r') == True:
		report = True
		noparms = False
	elif idarg(arg,'--suppress') == True or idarg(arg,'-s') == True:
		suppress = True
		noparms = False
	elif idarg(arg,'--nogen') == True or idarg(arg,'-ng') == True:
		genoutput = False
		noparms = False
	elif idarg(arg,'--nocolor') == True or idarg(arg,'-nc') == True:
		nocolor = True
	else:
		noparms = False
		ifn = arg
		if ifn == '':
			error('No inputFileName supplied')

if noparms == True:
	usage()
	raise SystemExit

if ifn == '':
	error('inputFileName not supplied')

try:
	ifh = open(ifn)
except:
	error('can\'t open inputFileName "%s" for reading' % (ifn,))

try:
	inputText = ifh.read()
except:
	try:
		ifh.close()
	except:
		pass
	error('Unable to read inputFileName "%s"' % (ifn,))

if gfn == True:
	try:
		fh = open(ofn,'w')
	except:
		try:
			ifh.close()
		except:
			pass
		error('Cannot open outputFileName "%s" for writing' % (ofn,))

icontent = ''
if mmff == True:
	try:
		mfh = open(mfn)
	except:
		error('Cannot open includeFileName "%s" for reading' % (mfn,))
	else:
		try:
			icontent = mfh.read()
		except:
			try:
				mfh.close()
			except:
				pass
			error('Cannot read includeFileName "%s"' % (mfn,))
		else:
			try:
				mfh.close()
			except:
				error('Could not close includeFileName "%s"' % (mfn,))

il = len(inputText)
if icontent != '':
	mod = macro()
	mod.do(icontent)
	o = mod.do(inputText)
else:
	o = str(macro(inputText))
ol = len(o)
	
if gfn == True:
	try:
		fh.write(o)
	except:
		error('Could not write outputFileName "%s"' % (ofn,))
		try:
			fh.close()
		except:
			pass
	try:
		fh.close()
	except:
		error('Could not close outputFileName "%s"' % (ofn,))
else:
	try:
		if genoutput == True:
			sys.stdout.write(o)
	except:
		error('Could not write to stdout')

if osx == True:
	if gfn == True:
		cmd = 'open "%s"' % (ofn)
		os.system(cmd)

if report == True:
	print lx('     Read ','green') + lx('%d' % (il,),'white')+lx(' characters','green')
	print lx('Generated ','green') + lx('%d' % (ol,),'white')+lx(' characters','green')
