import sys
import string

from coral.modeler.extension import *


if __name__ == "__main__":
	if len(sys.argv) != 2:
		print "usage: python mnf2shellscript.py <mnf-file>"
		sys.exit(1)

# File check start

	if sys.argv[1][-4:] != ".mnf":
		print "Error: not an .mnf file"
		sys.exit(2)

	try:
		f=open(sys.argv[1],"r")
	except IOError , e:
		sys.stderr.write(e.__str__()+'\n')
		sys.exit(3)

        f.close() # Close it again because the ExtensionRegistry will open it by it self
        
# File check end

        registry=ExtensionRegistry()
        registry.addManifest(sys.argv[1])
        


	edclass2attrib={
		"DiagramEditorToolbarEntry":"diagram_kind",	
		"DiagramElementCreator":"element_kind",	
		"DiagramElementExt":"element_kind",
		"DiagramCreator":"model_kind",
		"SimpleDiagramElementExt":"typeInfo",
		"PropertyEditor":"element_kind"
		}

	filename=sys.argv[1][:-4]+".mnf2shellscript.py"
	print "Writing ", filename
	
	try:
		outfile=open(filename,"w")
	except IOError, e:
		sys.stderr.write(e.__str__()+'\n')
		sys.exit(4)


	outfile.write("#START of script: "+filename+"\n\n")
	outfile.write("\n")
	outfile.write("package=coral.lang.CoralEx10.Package()\n")
	for ext in registry.extensions:
		outfile.write("try:\n")#TRY
		
		outfile.write("\tself=coral.lang.CoralEx10."+ext.type+"()\n")
		outfile.write("\tself.path=\""+ext.factoryName+"\"\n")
		outfile.write("\tself."+edclass2attrib[ext.type]+"=\""+ext.elementName+"\"\n")

		from_index=ext.elementName.rfind(':')+1
		outfile.write("\tself.name=\""+ext.elementName[from_index:]+"\"\n")

		outfile.write("\tpackage.ownedElement.append(self)\n")
		outfile.write("except coral.WFRException, e:\n")
		outfile.write("\tprint e.__str__()\n")
		outfile.write("\tprint \""+ext.type+" "+ext.elementName+" "+ext.factoryName+"\"\n")
	outfile.write("\n#END of script generated from "+sys.argv[1]+"\n")
	
