#!/usr/bin/env python
import coral
import time
import qt
from coral.modeler import modeler
from coral.modeler.util import fake_events

DI = coral.lang.XMIDI20

mw = modeler.ModelerWindow()
mw.main(loop=0)

p = coral.loadDocument("several_UML14_diagrams.xml")

all = coral.Set()

for r in p.contents():
    all.unionWith(r.__getAllParts__())

def get(coll, name):
    def samename(elem):
        try:
            return elem.name == name
        except:
            return False
    t = coll.select(samename)
    assert len(t) == 1
    return t[0]
    


model = get(all, "TheModel")

x_ges = model.__getSlotByOppositeName__(DI.Uml1SemanticModelBridge, "element").diagram

d = None
for x_ge in x_ges:
    assert x_ge.oclIsKindOf(DI.Diagram)
    if not x_ge.semanticModel.typeInfo == "ClassDiagram":
        continue
    d = x_ge
    break

assert d
print "DISPLAYING", d.name

#
# Find the class to move
#
#
def getClass(coll, name, diagram):
    c = get(coll, name)
    x_cs = c.__getSlotByOppositeName__(DI.Uml1SemanticModelBridge, "element").graphElement
    for x_c in x_cs:
        if x_c.container == d:
            return c, x_c
    return c, None

c1, x_c1 = getClass(all, "NewClass_1", d)

class RememberPosition:
    def __init__(self, graphElement):
        self.graphElement = graphElement
        self.oldx = int(graphElement.position.x)
        self.oldy = int(graphElement.position.y)

    def checkDelta(self, dx, dy):
        err1 = self.graphElement.position.x - int(self.oldx + dx)
        err2 = self.graphElement.position.y - int(self.oldy + dy)
        if err1 != 0 or err2 != 0:
            print "Delta X difference", err1
            print "Delta Y difference", err2
            assert 0

dv = mw.displayDiagram(d)
feg = fake_events.FakeMouse(mw, dv)

#
# Select it, move it -30,30 pixels
#
x = x_c1.position.x
y = x_c1.position.y
rp = RememberPosition(x_c1)
feg.press(x, y)
feg.move(x - 30, y + 30, 5)
feg.depress()
rp.checkDelta(-30, 30)

#
# Select several
#
c4, x_c4 = getClass(all, "NewClass_4", d)

sx = x - 30
sy = y + 30

feg.press(sx-5, sy-5)
feg.move(sx + 250, sy + 250, 5)
feg.depress()

sel = dv.getCurrentSelection()
print sel
assert x_c1 in sel
assert x_c4 in sel

#
# Move several
#
rp1 = RememberPosition(x_c1)
rp4 = RememberPosition(x_c4)

feg.press(sx+5, sy+5)
feg.deltaMove(30, 5, 5)
feg.depress()

rp1.checkDelta(30, 5)
rp4.checkDelta(30, 5)

time.sleep(1)
