#!/usr/bin/env python
import coral
import coral.modeler
import coral.modeler.modeler

TM = coral.getTransactionManager()

#mw = coral.modeler.modeler.ModelerWindow()
#mw.processEvents()

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

class_diagram = prj.contents()[1]
model = prj.contents()[0]

L = coral.lang.UML14
DI = coral.lang.XMIDI20
assert model.oclIsKindOf(L.Model)
assert class_diagram.oclIsKindOf(DI.Diagram)

c1 = model.ownedElement.select(lambda x: x.name == "NewClass_1")[0]
c2 = model.ownedElement.select(lambda x: x.name == "NewClass_2")[0]
c3 = model.ownedElement.select(lambda x: x.name == "NewClass_3")[0]
assoc = model.ownedElement.select(lambda x: x.oclIsKindOf(L.Association))[0]
assert c1
assert c2
assert c3
assert assoc

assert assoc.connection[0].participant == c1
assert assoc.connection[1].participant == c2

xc1 = c1.xmidi_get_graphelements()[0]
xc2 = c2.xmidi_get_graphelements()[0]
xc3 = c3.xmidi_get_graphelements()[0]

# No attributes
assert xc1.contained[2].contained[0].contained.size() == 0

TM.beginModifyCmd()
try:
    attr = L.Attribute(type = c2)
    c1.feature.append(attr)
finally:
    TM.endModifyCmd()

assert c1.feature.size() == 1
assert xc1.contained[2].contained[0].contained.size() == 1
xattr = attr.xmidi_get_graphelements()[0]
assert xattr == xc1.contained[2].contained[0].contained[0]

for i in xattr.contained:
    print i.semanticModel.element
assert xattr.contained.size() == 6
assert xattr.contained[-3].contained.size() == 1
assert xattr.contained[-3].contained[0].semanticModel.element == c2

TM.beginModifyCmd()
try:
    attr.type = c3
finally:
    TM.endModifyCmd()


assert xattr.contained.size() == 6
assert xattr.contained[-3].contained.size() == 1
assert xattr.contained[-3].contained[0].semanticModel.element == c3

prj.setFilename("tmp/changeAttributeType.xml")
coral.saveDocument(prj)
