#!/usr/bin/env python
import coral
from coral.modeler.outline import outlineeditor
import time
DI = coral.lang.XMIDI20
L = coral.meta.UML14

# Create window and display it
from coral.modeler import modeler, action
mw=modeler.ModelerWindow()
mw.processEvents()

TM = coral.getTransactionManager()
TM.beginModifyCmd()
try:
    prj = mw.newProject(L)
    
    m = prj.contents()[0]
    m.name = "myModel"
    
    p1 = L.Package(name = "P1")
    p2 = L.Package(name = "P2")
    c = L.Class(name = "C1")
    m.ownedElement.add(p1)
    m.ownedElement.add(p2)
    m.ownedElement.add(c)
finally:
    TM.endModifyCmd()

outliner = mw.getOutlineEditor()

mw.getDiagramEditorManager().editorSet.notifyFocusOn(c)

outline_qt_prj = outliner.qlvItems[prj]
outline_qt_m = outliner.qlvItems[m]
outline_qt_p1 = outliner.qlvItems[p1]
outline_qt_p2 = outliner.qlvItems[p2]
outline_qt_c = outliner.qlvItems[c]
assert outline_qt_p1.parent() == outline_qt_m
assert outline_qt_p2.parent() == outline_qt_m
assert outline_qt_m.parent() == outline_qt_prj
assert outline_qt_c.parent() == outline_qt_m

mw.processEvents()

# Move c1 from m to p1
TM.beginModifyCmd()
try:
    c.namespace = p1
finally:
    TM.endModifyCmd()

mw.processEvents()

time.sleep(2)

assert outline_qt_p1.parent() == outline_qt_m
assert outline_qt_p2.parent() == outline_qt_m
assert outline_qt_m.parent() == outline_qt_prj
assert outline_qt_c.parent() in [ None, outline_qt_p1, outline_qt_p2 ]

# Open p2
outline_qt_p2.setOpen(True)
mw.processEvents()
time.sleep(2)

# Move c1 from p1 to p2

TM.beginModifyCmd()
try:
    c.namespace = p2
finally:
    TM.endModifyCmd()

mw.processEvents()

assert outliner.qlvItems[c] == outline_qt_c

time.sleep(2)

assert outline_qt_p1.parent() == outline_qt_m
assert outline_qt_p2.parent() == outline_qt_m
assert outline_qt_m.parent() == outline_qt_prj
print "c", outline_qt_c.parent()
print "p1", outline_qt_p1
print "p2", outline_qt_p2
assert outline_qt_c.parent() == outline_qt_p2

# Move c1 from p2 back to m

TM.beginModifyCmd()
try:
    c.namespace = m
finally:
    TM.endModifyCmd()

mw.processEvents()

time.sleep(2)

for k,v in outliner.qlvItems.iteritems():
    print "KV", k, v

assert outliner.qlvItems[c] == outline_qt_c
assert outline_qt_p1.parent() == outline_qt_m
assert outline_qt_p2.parent() == outline_qt_m
assert outline_qt_m.parent() == outline_qt_prj
print "c", outline_qt_c.parent()
print "p1", outline_qt_p1
print "p2", outline_qt_p2

assert outline_qt_c.parent() == outline_qt_m
