#!/usr/bin/python
#
# create_file_entries.py
#   automatically generate checks for changes to config files
#
 
import sys, csv, re, types
import fileinput

'''
Autovivification used to generate nested dictionaries.
'''
class AutoViv(dict):
        def __getitem__(self, item):
                try:
                        return dict.__getitem__(self, item)
                except KeyError:
                        value = self[item] = type(self)()
                        return value

'''
Some formatting functions
'''
def remove_quotes(string2):
	return re.sub("\"", "", string2)

def clean_line(string):
	string = remove_quotes(string)
	string = string.strip()
        string = re.sub("-", "\\-", string)
        string = re.sub("\/", "\/", string)
        string = "^" + string
        string = re.sub("[\s]", "[\s]+", string)
        string = string + "\\s*$"
	return string

'''
Read in the test input files and generate nested dictionaries.
'''
def create_dictionary():
	test_id = ""
	testname = ""
	ovaldict = AutoViv()
	for line in fileinput.input("test_input_1_entry"):
		line = line.rstrip()
		if (re.match("^\w", line)):
			test_id = line.strip()
			test_id = re.sub("\:", "", test_id)
		
		elif (re.match("^\t[^.=\t]", line)):
			if (re.match("^title\:", line.strip())):
				ovaldict[test_id]["title"] = re.sub("title\:", "", line.strip())
				ovaldict[test_id]["title"] = remove_quotes(ovaldict[test_id]["title"])
			elif(re.match("^cces\:", line.strip())):
				ovaldict[test_id]["cces"] = re.sub("cces\:", "", line.strip())
				ovaldict[test_id]["cces"] = remove_quotes(ovaldict[test_id]["cces"]) 
			elif(re.match("^desc\:", line.strip())):
				ovaldict[test_id]["desc"] = re.sub("desc\:", "", line.strip())
			 	ovaldict[test_id]["desc"]  = remove_quotes(ovaldict[test_id]["desc"])
			
		elif(re.match("^\t\t[^.=\t]", line)):
			testname = re.sub("\:", "", line.strip())
			testname = remove_quotes(testname).strip()

		elif(re.match("^\t\t\t[^.=\t]",line)):
			if(re.match("^filepath\:", line.strip())):
				ovaldict[test_id][testname]["filepath"]  = re.sub("filepath\:", "", line.strip())
				ovaldict[test_id][testname]["filepath"] =  remove_quotes(ovaldict[test_id][testname]["filepath"]).strip()
			elif(re.match("^filename\:", line.strip())):
				ovaldict[test_id][testname]["filename"]  = re.sub("filename\:", "", line.strip())
				ovaldict[test_id][testname]["filename"]  = remove_quotes(ovaldict[test_id][testname]["filename"]).strip()

			elif(re.match("^line\:", line.strip())):
				ovaldict[test_id][testname]["line"]  = re.sub("line\:", "", line.strip())
			 	ovaldict[test_id][testname]["line"] = clean_line(ovaldict[test_id][testname]["line"]).strip()
	return ovaldict

'''
Put dictionary entries into template and output.
'''
def outputter(ovaldict):
	for defs in ovaldict.iterkeys():
		test_id = defs
		test_title = ovaldict[defs]["title"]
		cce_id = ovaldict[defs]["cces"]
		description = ovaldict[defs]["desc"]
		critstring = ""
		temp_critstring = ""
		test_string = ""
		temp_teststring = ""
		tests = ovaldict[defs].iterkeys()
		template2 = ""
		
		with open("./template_file_entries", 'r') as templatefile:
			for lines in templatefile.readlines():
				template2 += lines
				if re.search("ind\:", lines):
					temp_teststring += lines
				if re.search("criterion", lines):
					temp_critstring = lines
			
			filestring = template2
			
			for testnames in tests:
				if type(ovaldict[defs][testnames]) == AutoViv:
					critstring += temp_critstring.replace("TESTID", test_id).replace("TESTNAME", testnames)
					test_string += temp_teststring.replace("TESTID", test_id).replace("TESTNAME", testnames).replace("FILEPATH", ovaldict[defs][testnames]["filepath"]).replace("FILENAME", ovaldict[defs][testnames]["filename"]).replace("FILE_LINE", ovaldict[defs][testnames]["line"])

			filestring = filestring.replace(temp_critstring, critstring)
			filestring = filestring.replace(temp_teststring, test_string)

			filestring = filestring.replace("TESTTITLE", test_title)
			filestring = filestring.replace("TESTID", test_id)
                        filestring = filestring.replace("CCE_ID", cce_id if cce_id else "TODO")
                        filestring = filestring.replace("DESC", description)

            	with open("./output/" + defs  + ".xml", 'wb+') as outputfile:
               		outputfile.write(filestring)
               		outputfile.close()


def main():
    	outputter(create_dictionary())
	sys.exit(0)

if __name__ == "__main__":
    main()

