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

TM = coral.getTransactionManager()

## Checking that original model is OK

prj = coral.loadDocument("4classes1gen.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 == "C1")[0]
c2 = model.ownedElement.select(lambda x: x.name == "C2")[0]
c3 = model.ownedElement.select(lambda x: x.name == "C3")[0]
c4 = model.ownedElement.select(lambda x: x.name == "C4")[0]
gen = model.ownedElement.select(lambda x: x.oclIsKindOf(L.Generalization))[0]

assert c1
assert c2
assert c3
assert c4
assert gen

assert gen.child == c1
assert gen.parent == c2


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


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

ge = graphedges[0]

assert ge.anchor[0] in  xc1.anchorage
assert ge.anchor[1] in  xc2.anchorage

## 1 ## Now delete class C1

TM.beginModifyCmd()
try:
    c1.namespace = None
finally:
    TM.endModifyCmd()

assert not gen.child

#For this change, check anchors
assert ge.anchor[0] not in xc1.anchorage

## 2 ## Now relink client to c3
TM.beginModifyCmd()
try:
    gen.child = c3
finally:
    TM.endModifyCmd()

assert gen.child
assert len(ge.anchor) == 2

## Check anchors
assert ge.anchor[0] in xc3.anchorage

## 3 ## Now delete class C2
TM.beginModifyCmd()
try:
    c2.namespace = None
finally:
    TM.endModifyCmd()

assert not gen.parent
#Note anchor[1] is removed
assert len(ge.anchor) == 1

assert ge.anchor[0] not in xc2.anchorage


## 4 ## Now relink supplier to c4
TM.beginModifyCmd()
try:
    gen.parent = c4
finally:
    TM.endModifyCmd()

assert gen.parent
assert len(ge.anchor) == 2

## Check anchors
assert ge.anchor[1] in xc4.anchorage





















### 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)
