#!/usr/bin/env python
import coral
#import math
import random

from coral.modeler import modeler,action
import coral.modeler.diagram
from coral.modeler.diagram import di_support as DISUPP

def moveGraphNodeRandomly(graphNode):
    graphNode.position.x=random.random()*500
    graphNode.position.y=random.random()*500

def checkGraphConnectorAgainstEndWpPosition(graphEdge):
    startWp=graphEdge.waypoints[0]
    endWp=graphEdge.waypoints[-1]

    start_connector=graphEdge.anchor[0]
    end_connector=graphEdge.anchor[1]
    connector_sP = DISUPP.localToGlobalPosition(start_connector.graphElement,start_connector.position.x,start_connector.position.y)
    connector_eP = DISUPP.localToGlobalPosition(end_connector.graphElement,end_connector.position.x,end_connector.position.y)

    assert abs(connector_sP[0]- startWp.x) < 0.1
    assert abs(connector_sP[1]- startWp.y) < 0.1

    assert abs(connector_eP[0]- endWp.x) < 0.1,str(abs(connector_eP[0]- endWp.x))
    assert abs(connector_eP[1]- endWp.y) < 0.1,str(abs(connector_eP[1]- endWp.y))


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

#Locate diagram in prj

for root in prj.contents():
    if root.oclIsKindOf(coral.lang.XMIDI20.Diagram):
        diag=root
        break
        
#Move graphnodes one by one

m=modeler.ModelerWindow()
m.main(loop=0)
m.getDiagramEditorManager().editorSet.notifyFocusOn(diag)
m.processEvents()

print "First check that original is OK"
for part in diag.__getAllParts__():
    if part.oclIsKindOf(coral.lang.XMIDI20.GraphEdge):
        checkGraphConnectorAgainstEndWpPosition(part)

print "Move graphnodes around"
coral.getTransactionManager().beginModifyCmd()
try:
    for part in diag.contained:
        if part.oclIsKindOf(coral.lang.XMIDI20.GraphNode):
            moveGraphNodeRandomly(part)
finally:
    coral.getTransactionManager().endModifyCmd()
m.processEvents()


#Check that all edges have been layed out
# by comparing the graphconnector global
# position to the end waypoint position

print "Then check that layed out is OK"
for part in diag.__getAllParts__():
    if part.oclIsKindOf(coral.lang.XMIDI20.GraphEdge):
        checkGraphConnectorAgainstEndWpPosition(part)
