#!/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]

graphedges = assoc.xmidi_get_graphelements()
assert len(graphedges) == 1

ge = graphedges[0]
assert ge.anchor[0] == xc1.anchorage[0]
assert ge.anchor[1] == xc2.anchorage[0]

TM.beginModifyCmd()
try:
    assoc.connection[0].participant = c3
finally:
    TM.endModifyCmd()

# Now the XMI-DI should also have been updated
assert assoc.connection[0].participant == c3
assert assoc.connection[1].participant == c2
assert ge.anchor[0] == xc3.anchorage[0]
assert ge.anchor[1] == xc2.anchorage[0]

# BUG for some reason the coordinates aren't updated.
# Probably because the diagram isn't visible on-screen
# during this test.
# However they are updated when we jiggle one of the classes
# a bit...

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