#!/usr/bin/env python
import os
from coral.modeler import modeler
import coral
import time
import math

#from coral.modeler.diagram.presentation import WaypointWrapper


## Test if all waypoints corresponds to widgets points
def cmpPoints2WPoints(points, wps):
    assert len(points) == len(wps)
    i = 0
    for p in points:
        assert abs(p[0] - wps[i].x) < 0.5 ## Tolerance = 0.5
        assert abs(p[1] - wps[i].y) < 0.5
        i=i+1


XMIDI = coral.lang.XMIDI20
UML14 = coral.lang.UML14

m=modeler.ModelerWindow()
storage=m.openProject("./clswithwp.xmi")
m.main(loop=0)


diagram = None
for r in storage.contents():
    if r.oclIsKindOf(XMIDI.Diagram) and r.semanticModel.typeInfo == "ClassDiagram":
        diagram = r
        break

assert diagram

canvas = diagram.widget.__getPyValue__()

print "DIAGRAM", diagram
m.getDiagramEditorManager().editorSet.notifyFocusOn(diagram)

m.processEvents()

anedge_di = None
for e in diagram.contained:
    if e.semanticModel.element.__type__() == UML14.Association:
        anedge_di = e
        break

waypts = anedge_di.waypoints
the_widget = anedge_di.widget.__getPyValue__()
widgetpts = the_widget.points

assert len(waypts) == 2
assert len(widgetpts) == 2

cmpPoints2WPoints(widgetpts, waypts)


##======== Add one waypoint

coral.getTransactionManager().beginModifyCmd()
try:
    waypts.insert(XMIDI.Point(x=float(300), y=float(300)), 1)
finally:
    coral.getTransactionManager().endModifyCmd()

m.processEvents()

widgetpts = the_widget.points

assert len(waypts) == 3
assert len(widgetpts) == 3

assert widgetpts[1][0] == float(300)
assert widgetpts[1][1] == float(300)

cmpPoints2WPoints(widgetpts, waypts)

##========= Move one waypoint

coral.getTransactionManager().beginModifyCmd()
try:
    waypts[1].x = 400
    waypts[1].y = 400
finally:
    coral.getTransactionManager().endModifyCmd()

m.processEvents()

widgetpts = the_widget.points

assert widgetpts[1][0] == float(400)
assert widgetpts[1][1] == float(400)

cmpPoints2WPoints(widgetpts, waypts)

##========= Delete one waypoint

coral.getTransactionManager().beginModifyCmd()
try:
    waypts.drop_index(1)
finally:
    coral.getTransactionManager().endModifyCmd()    

m.processEvents()

widgetpts = the_widget.points

assert len(waypts) == 2
assert len(widgetpts) == 2

cmpPoints2WPoints(widgetpts, waypts)


