#!/usr/bin/env python
import coral
import coral.modeler
import coral.modeler.modeler
from coral.modeler import xmidigraphbuilder
import coral.modeler.diagram.xmidi_diagrams as diagrams

TM = coral.getTransactionManager()

## Checking that original model is OK

prj = coral.loadDocument("testMultipleStereotypes.xml")

model = prj.contents()[0]

assert model

L = coral.lang.UML14
DI = coral.lang.XMIDI20
assert model.oclIsKindOf(L.Model)


c1 = model.ownedElement.select(lambda x: x.name == "C1")[0]
st1 = model.ownedElement.select(lambda x: x.name == "ST1")[0]
st2 = model.ownedElement.select(lambda x: x.name == "ST2")[0]
st3 = model.ownedElement.select(lambda x: x.name == "ST3")[0]

assert c1
assert st1
assert st2
assert st3

assert st1 in c1.stereotype
assert st2 in c1.stereotype
assert st3 in c1.stereotype

diagram = None

TM.beginModifyCmd()
try:
    diagram = diagrams.createDiagram(model.__getRootsProject__(), typeinfo="ClassDiagram", owner_elem=model)
    assert diagram
    xmidigraphbuilder.xmidibuilder(model, diagram) 

finally:
    TM.endModifyCmd()


xc1 = c1.xmidi_get_graphelements()[0]

nc = None
for c in xc1.contained:
    if c.semanticModel.typeInfo == "NameCompartment":
        nc = c

assert nc

n_of_stc = 0
for stc in nc.contained:
    if stc.semanticModel.typeInfo == "StereotypeCompartment":
        n_of_stc += 1



assert n_of_stc == 1

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

assert not model.ownedElement.select(lambda x: x.name == "ST1")
assert not model.ownedElement.select(lambda x: x.name == "ST2")

assert len(c1.stereotype) == 1

n_of_stc = 0
for stc in nc.contained:
    if stc.semanticModel.typeInfo == "StereotypeCompartment":
        n_of_stc += 1

assert n_of_stc == 1

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

assert not model.ownedElement.select(lambda x: x.name == "ST3")

assert not model.ownedElement.select(lambda x: x.oclIsKindOf(L.Stereotype))

n_of_stc = 0
for stc in nc.contained:
    if stc.semanticModel.typeInfo == "StereotypeCompartment":
        n_of_stc += 1

assert n_of_stc == 0

