#!/usr/bin/env python
import qt
import time

import coral
import coral.modeler.modeler
from coral.modeler.diagram.demanager import DiagramEditorManager


class FakeDropEvent(qt.QDropEvent):
    def __init__(self, str, point):
        qt.QDropEvent.__init__(self, point)
        self.str = str
        
    def format(self, index):
        print "FORMAT", index
        if index == 0:
            return "text/xml"
        return None
    
    def encodedData(self, format):
        print "encodedData", format
        return self.str


DI = coral.lang.XMIDI20
mw = coral.modeler.modeler.ModelerWindow()

xcoord = 40

def tst(prj):
    m = prj.contents()[0]
    m_x = prj.contents()[1]
    
    c = m.ownedElement[0]
    c_x = c.xmidi_get_graphelements()[0]
    
    # Shows diagram
    mw.notifyFocusOn(c_x.container)
    mw.notifyFocusOn(c)
    mw.processEvents()
    
    assert len(m_x.contained) == 1

    ########## DROPPING ON CANVAS
    
    #### This locks QT until you press the mouse button??
    ####dragged = mw.outlineEditor.startDrag()
    
    #e = mw.getDiagramEditorManager().editorTab
    #print e, "with", e.count()
    #for i in range(e.count()):
    #    print e.page(i)
    #mw.processEvents()
    
    d = mw.displayDiagram(m_x)
    print d
    assert d
    print "d is", d


    o = coral.Set()
    dobj = coral.lang.CoralEx10.InternalQtDragAndDrop.DragAndDrop()
    dobj.linkedContents = [ c ]
    o.add(dobj)
    str = coral.saveDocument_str(o, "2.0")
    global xcoord
    p = qt.QPoint(xcoord, 40)
    xcoord += 100
    dropped = FakeDropEvent(str, p)
    
    d.dropEvent(dropped)
    
    print "PROCESSING EVENTS"
    mw.processEvents()
    time.sleep(2)
    
    m_x_again = m.xmidi_get_diagrams()[0]
    print m_x, m_x_again
    assert m_x == m_x_again
    assert len(m_x.contained) == 2
    tm = coral.getTransactionManager()
    tm.beginModifyCmd()
    try:
        # Doesn't matter if we take [0] or [1]
        c2_x = c.xmidi_get_graphelements()[0]
        c2_x.container = None
    finally:
        tm.endModifyCmd()
    print "SLEEPING"
    mw.processEvents()
    time.sleep(2)

_prj = coral.loadDocument("simple_drag_diagram.xmi")
tst(_prj)

# We have had some problems with the reference information
# in projects not getting updated. This tests for it, since
# the new project "prj" does not have any reference information calculated
prj = coral.Project()
for e in _prj.contents():
    e.__setProject__(prj)

tst(prj)
