#!/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

st=coral.Project()

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

c1=L.Class(name="One")
c2=L.Class(name="Two")
p.ownedElement.insert(c1)
p.ownedElement.insert(c2)

association=L.Association(name="A")
end1=L.AssociationEnd(association=association, participant = c1)
end2=L.AssociationEnd(association=association, participant = c2)
association.connection.append(end1)
association.connection.append(end2)

dependency=L.Dependency(name="D")
dependency.client.append(c1)
dependency.supplier.append(c2)

generalization=L.Generalization(name="G")
generalization.child=c1
generalization.parent=c2

p.ownedElement.insert(association)
p.ownedElement.insert(dependency)
p.ownedElement.insert(generalization)

#
#Crate a diagram for the model
#

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

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

#
#Check if all parts really exist in their right places
#
assert len(cd.contained)==5
#Diagram contains 2 Classnodes + 3 Edges

for ge in cd.contained:
    if ge.oclIsKindOf(DI.GraphEdge):
        assert len(ge.contained)==1 or len(ge.contained)==3
        #Edges contains 1 nameNode + (if association) 2 associationEndNodes

#
#Check if classes have correct anchorage and edges have correct anchors
#
for ge in cd.contained:

    if ge.oclIsKindOf(DI.GraphNode):
        assert len(ge.anchorage)==3

        for a in ge.anchorage:       #Check if the anchorages and anchors point
            elems = {}               #to edges and back to the classnodes
            for ea in a.graphEdge[0].anchor:
                elems[ea.graphElement]=True
            assert ge in elems.keys()

    if ge.oclIsKindOf(DI.GraphEdge):
        assert len(ge.anchor)==2

#
#Save the whole thing to an xmi file
#

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

