#!/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 import xmidigraphbuilder
from coral.modeler.diagram import xmidi_diagrams

L = coral.lang.UML14

def isInList(list,item):
    assert list
    for i in list:
        if i == item:
            return True
    return False

def hasChild( container, element):
    for elem in container.contained:
        if elem==element:
            return True
        if hasChild( elem, element):
            return True
    return False

def returnContained(container, typeinfo):
    a = []
    for elem in container.contained:
        if elem.semanticModel.typeInfo==typeinfo:
            a.append(elem)
    return a


st=coral.Project()

p=L.Package()
p.__setProject__(st)

c=L.Class()
p.ownedElement.append(c)

attribute=L.Attribute()
operation=L.Operation()
stereotype=L.Stereotype()

c.feature.insert(attribute)
c.feature.insert(operation)
c.stereotype.insert(stereotype)
p.ownedElement.append(stereotype)

#
#Crate a diagram for the model
#

cd = xmidi_diagrams.createDiagram(st, owner_elem=p, typeinfo="ClassDiagram")

#
#Run the builder
#
xmidigraphbuilder.xmidibuilder(p, cd)


def checkClassCompartments(cls):
    compseps = returnContained(cls,"CompartmentSeparator")
    attrcomps = returnContained(cls,"AttributeCompartment")
    opcomps = returnContained(cls,"OperationCompartment")
    namecomps = returnContained(cls,"NameCompartment")

    # Class contains 5 compartments
    # (2 compartment separators, 1 operation compartment, 1 attribute compartment, 1 Name compartment)
    assert len(cls.contained)==5
    assert len(compseps) == 2
    assert len(attrcomps) == 1
    assert len(opcomps) == 1
    assert len(namecomps) == 1

    # attributes = first attributecomp.first delim. sect
    attrs = attrcomps[0].contained[0].contained
    assert len(attrs) == 1
    
    # operations = first operationcomp.first delim. sect
    ops = opcomps[0].contained[0].contained
    assert len(attrs) == 1

    stereotypes = returnContained(namecomps[0], "StereotypeCompartment")
    assert len(stereotypes) == 1
    
    name = returnContained(namecomps[0], "Name")
    assert len(name) == 1

    # Uncomment this when expression compartment is implemented
    # exps = returnContained(namecomps[0], "ExpressionCompartment")
    # assert len(exps) == 1
    
#
#Check if all parts really exist in their right positions
#

assert len(cd.contained)==2 #Diagram contains 1 Class and 1 Stereotype
cls=None
# get the graphElement of the Class
for gn in cd.contained:
    if gn.semanticModel.element==c:
        cls=gn
assert cls
checkClassCompartments(cls)



#
#Save the whole thing to an xmi file
#

st.setFilename("tmp/testXMIBuilder.xmi")
st.setXMIFormat("2.0")
coral.saveDocument(st)

