# runs and matches lines.  sticks parameters into a tuple.  some formatting issues in tuple.  parm name
# put in with leading blanks.  Could put in using match group to fix maybe...

# does not handle commented psp commands

true = 1
false = 0
MaxLineLength = 85

runInPSP = true
debug = false

if not runInPSP:
	Environment = {'key': 1}

if runInPSP:
	from PSPApp import *

import sys, re, string, types, os, traceback

import locale		# we need to specifically set the locale to C since the OS setting
					# may override the default locale

from PSPTools import *
import PSPScriptMsgs
import PSPScriptPyBlocks

from PSPScriptParse import *

# display exception info
def PrintException():
	excType, excVal, excTraceBack = sys.exc_info()
	print str(excType)
	print str(excVal)
	#print str(excTraceBack)
	traceback.print_exc(file=sys.stdout)
	
#******************************************************************************
#   Function:    Convert()
#   Author:      Steve Neumeyer
#   Purpose:     Convert result from old parser code into something we can parse in
#				 the Python/C API once this gets into PSP
#   Returns:     a list of dictionaries that contain various keys describing what kind of
#				 block has been parsed and its attributes
#   Parameters:  the output from the parser, and the 'Envrionment' dictionary
#   Notes:       
#******************************************************************************
def Convert(sp, Environment):
	struct = []

	propertiesBlock = false

	# if no script properties block, add one
	for pyBlock in sp.pyBlocks:
		if pyBlock.commandType == 'Script Properties':
			propertiesBlock = true

	if propertiesBlock == false:
		return None

	for pyBlock in sp.pyBlocks:
		Dict = {}
		Dict['type'] = pyBlock.commandType
		# print Dict['type']

		# need to add a cr for command and commented command types		
#		if Dict['type'] == "PSPCmd" or Dict['type'] == "CmtedPSPCmd":
#			Dict['text'] = pyBlock.block + '\n'
#		else:
#			Dict['text'] = pyBlock.block
		Dict['text'] = pyBlock.block

		if Dict['type'] == "PSPCmd" or Dict['type'] == "CmtedPSPCmd":
			if Dict['type'] == "CmtedPSPCmd":
				Dict['PR'] = GetDictFromCmdString( RemoveComments(pyBlock.block) )
			else:
				Dict['PR'] = GetDictFromCmdString( pyBlock.block )
		elif Dict['type'] == "Script Properties":
			Dict['PR'] = GetPropertiesDict( pyBlock.block )
		else:
			Dict['PR'] = {}
			
		if pyBlock.commandType == 'PSPCmd' or pyBlock.commandType == 'CmtedPSPCmd':
			if pyBlock.commandType == 'CmtedPSPCmd':
				commandinfo = GetQuotedFields( RemoveComments(pyBlock.block) )
			else:				
				commandinfo = GetQuotedFields( pyBlock.block )
			if runInPSP:
				AllCmdInfo = App.Do(Environment, 'GetCommandInfo', {
					'TargetCmd': commandinfo[0], 
					'GeneralSettings': {
						'ExecutionMode': App.Constants.ExecutionMode.Default
					}, 
					'ParamInfo': App.Constants.ParamInfo.None
					})
				Dict['localCommandName'] = AllCmdInfo['LocalName']
				editable = 0
				for x in AllCmdInfo['ResourceAttributes']:
					if x[0] == 'IsEditable':
						editable = x[1]
				if editable != 0:
					Dict['editable'] = 'Editable'
				else:
					Dict['editable'] = 'NOTEditable'
			else:
				Dict['editable'] = "NOTEditable"
				Dict['localCommandName'] = ""
			Dict['commandName'] = commandinfo[0]
		else:
			Dict['editable'] = "NOTEditable"
			Dict['localCommandName'] = ""
			Dict['commandName'] = ""
			
		struct += [Dict]

	return struct	
	
#******************************************************************************
#   Function:    Do()
#   Author:      Carl Lestor
#   Purpose:     Script main loop. Get a script name from the user, parse it,
#			 	 create a GUI from it, then run the Tk mainloop()
#   Returns:     
#   Parameters:  
#   Notes:       
#******************************************************************************
def Do(Environment):
	# set the locale to C (the default) so that eval() will work properly with real numbers
	locale.setlocale(locale.LC_NUMERIC, 'C')
	
	# construct instance
	sp = ParseScript()
	userFileName = ""
	val = None

	if Environment.has_key('__scriptpath__') and runInPSP:
		# print 'ENVIRONMENT DICT'
		# print Environment['__scriptpath__']
		userFileName = Environment['__scriptpath__']		
	else:
		print 'ERROR: CmdEditScript did not specify a filename'

	# print 'USER FILE NAME'
	# print userFileName

	sp, parseResult = DoParse(userFileName, sp)

	if (parseResult[0]):
		#print "SP"
		#print sp
		#print 'parse result'
		#print parseResult
		# print sp.errorString

		try:
			val = Convert(sp, Environment)
		except (NameError, SyntaxError, IndexError):
			if debug:
				print "Unexpected Error: ", sys.exc_info()[0]
				print "Trackback: \n", traceback.print_tb(sys.exc_info()[2])
			val = None
		except:
			print "Unexpected Error: ", sys.exc_info()[0]
			print "Trackback: \n", traceback.print_tb(sys.exc_info()[2])
		return val
	else: # parse failed
		return None 

	#return Convert(sp, Environment)

# Main function, run when invoked as a stand-alone Python program.
if __name__ == '__main__':
	Do(Environment)
