#!/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()
c1.name = "Class 1"
m1.ownedElement.insert(c1)

c2=L.Class()
c2.name = "Class 2"
m1.ownedElement.insert(c2)



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

cd.__setProject__(prj)
cd2.__setProject__(prj)

xmidibuilder(m1, cd)
xmidibuilder(m1, cd2)

diagrams=m1.xmidi_get_diagrams()
assert cd
assert diagrams

def count_elements(prj):
    n = 0
    for root in prj.contents():
        n += root.__getAllParts__().size()
    return n

def class_should_have(theclass, n_attributes):
    GNs = theclass.xmidi_get_graphelements()
    for gn in GNs:
        attrcomp1 = searchForSimpleGraphNode(gn.contained, "AttributeCompartment")
        delimitedsect1 = searchForSimpleGraphNode(attrcomp1.contained, "DelimitedSection")
        assert len(delimitedsect1.contained) == n_attributes

class_should_have(c1, 0)
class_should_have(c2, 0)
    
# add an attribute to class "c1"
a1=L.Attribute()
a1.name = "MyAttribute"


n_elements = -1
for i in xrange(10):
    coral.getTransactionManager().beginModifyCmd()
    try:
        
        c1.feature.append(a1)
    finally:
        coral.getTransactionManager().endModifyCmd()

    if n_elements == -1:
        n_elements = count_elements(prj)
    assert count_elements(prj) == n_elements

    # check that the XMIDI has updated correctly
    class_should_have(c1, 1)
    class_should_have(c2, 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
    class_should_have(c1, 0)
    class_should_have(c2, 1)
    
    assert count_elements(prj) == n_elements

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