#!/usr/bin/env python

import coral
import coral.util.transform.transform as T

UML=coral.lang.UML14
TM=coral.getTransactionManager()

prj=coral.loadDocument("testTransUML.xml")

userModel=None
transformations=None

for model in prj.contents():
    if model.oclIsKindOf(coral.lang.XMIDI20.Diagram):
        continue
    if model.name == "UserModel":
        userModel=model
    if model.name == "Transformations":
        transformations=model

assert userModel
assert transformations
sorted_trans={}
for transformation in transformations.ownedElement.select(lambda e: e.oclIsKindOf(UML.Package)):
    sorted_trans[str(transformation.name)]=transformation

keys=sorted_trans.keys()
keys.sort()
for name in keys:
    trans=sorted_trans[name]
    print "Running ",name
    lhs_package=trans.ownedElement.select(lambda e: e.name=="LHS")[0]
    rhs_package=trans.ownedElement.select(lambda e: e.name=="RHS")[0]
    lhs=lhs_package.ownedElement
    rhs=rhs_package.ownedElement
    before=len(userModel.ownedElement)
    TM.beginModifyCmd()
    try:
        T.transform(userModel, lhs, rhs)
    finally:
        TM.endModifyCmd()
    after=len(userModel.ownedElement)
    assert (after-before)==int(str(trans.taggedValue[0].dataValue))

#assert len(userModel.ownedElement) == 15, "Is "+str(len(userModel.ownedElement))
prj.setFilename("tmp/testTransformUMLoutput.xml")
coral.saveDocument(prj)
