#!/usr/bin/env python
from coral.modeler.diagram.degen import *
from coral import modeler
from coral.modeler.modeler import *
DI = coral.lang.XMIDI20
from coral.modeler.xmidigraphbuilder import xmidibuilder
from coral.modeler.diagram import xmidi_diagrams
import time

def searchForSimpleGraphNode(cset, ti):

    if cset:
        for c in cset:
            if c.semanticModel.oclIsKindOf(DI.SimpleSemanticModelElement) and c.semanticModel.typeInfo == ti:
                return c
    else:
        return None
    
L=coral.lang.UML14

m=ModelerWindow()
m.main(loop=0)

prj=coral.Project()

# insert UML14:Model to project
m1=L.Model()
m1.__setProject__(prj)

# insert two classes to the model
c1=L.Class()
m1.ownedElement.insert(c1)

c2=L.Class()
m1.ownedElement.insert(c2)



#create a Class Diagram for the model
cd=xmidi_diagrams.createDiagram(prj,owner_elem=m1,typeinfo="ClassDiagram")

xmidibuilder(m1, cd)

diagrams=m1.xmidi_get_diagrams()
assert cd
assert diagrams

# check that the XMIDI is correct before transactions
c1GNs = c1.xmidi_get_graphelements()
for gn in c1GNs:
    attrcomp1 = searchForSimpleGraphNode(gn.contained, "AttributeCompartment")
    delimitedsect1 = searchForSimpleGraphNode(attrcomp1.contained, "DelimitedSection")
    assert len(delimitedsect1.contained)==0
    
c2GNs = c2.xmidi_get_graphelements()
for gn in c2GNs:
    attrcomp2 = searchForSimpleGraphNode(gn.contained, "AttributeCompartment")
    delimitedsect2 = searchForSimpleGraphNode(attrcomp2.contained, "DelimitedSection")
    assert len(delimitedsect2.contained)==0
    
# add an attribute to class "c1"
a1=L.Attribute()
coral.getTransactionManager().beginModifyCmd()
try:
    
    c1.feature.append(a1)
finally:
    coral.getTransactionManager().endModifyCmd()

# check that the XMIDI has updated correctly
assert len(delimitedsect1.contained)==1
assert len(delimitedsect2.contained)==0

# move the attribute to class "c2"
coral.getTransactionManager().beginModifyCmd()
try:
    c2.feature.append(a1)
finally:
    coral.getTransactionManager().endModifyCmd()


# check that the XMIDI has updated correctly
assert len(delimitedsect2.contained)==1
assert len(delimitedsect1.contained)==0
