#!/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("4states1trans.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)


stm = model.ownedElement.select(lambda x: x.name == "STM")[0]

assert stm.oclIsKindOf(L.StateMachine)
tr = stm.transitions.select(lambda x: x.oclIsKindOf(L.Transition))[0]
s1 = stm.top.subvertex.select(lambda x: x.name == "S1")[0]
s2 = stm.top.subvertex.select(lambda x: x.name == "S2")[0]
s3 = stm.top.subvertex.select(lambda x: x.name == "S3")[0]
s4 = stm.top.subvertex.select(lambda x: x.name == "S4")[0]



assert s1
assert s2
assert s3
assert s4
assert tr

assert tr.source == s1
assert tr.target == s2


xs1 = s1.xmidi_get_graphelements()[0]
xs2 = s2.xmidi_get_graphelements()[0]
xs3 = s3.xmidi_get_graphelements()[0]
xs4 = s4.xmidi_get_graphelements()[0]


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

ge = graphedges[0]

assert ge.anchor[0] in  xs1.anchorage
assert ge.anchor[1] in  xs2.anchorage

## 1 ## Now delete class C1

TM.beginModifyCmd()
try:
    s1.container = None
finally:
    TM.endModifyCmd()

assert not tr.source

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

## 2 ## Now relink client to c3
TM.beginModifyCmd()
try:
    tr.source = s3
finally:
    TM.endModifyCmd()

assert tr.source
assert len(ge.anchor) == 2

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

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

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

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


## 4 ## Now relink supplier to c4
TM.beginModifyCmd()
try:
    tr.target = s4
finally:
    TM.endModifyCmd()

assert tr.target
assert len(ge.anchor) == 2

## Check anchors
assert ge.anchor[1] in xs4.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)
