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

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

m=modeler.ModelerWindow()
prj=m.openProject("../../../qa/models2import/Softsale.xmi")
m.main(loop=0)


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

assert diagram

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

m.processEvents()

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

assert aclass_di

m.getDiagramEditorManager().focusOn(aclass_di)

aclass = aclass_di.semanticModel.element
assert aclass
m.getDiagramEditorManager().editorSet.notifyFocusOn(aclass_di)
sw=m.getShell()


the_widget = aclass_di.widget.__getPyValue__()
assert the_widget is not None
assert the_widget.canvas() is not None

action.shellSetCurrentScript("self.isVisible = 0")
import time
start_time = time.time()
action.shellExecuteCurrentScript()
end_time = time.time()
res = action.shellGetOutput()
print "RESULT", res
print "FOO", aclass, aclass.namespace
print "TIME", end_time - start_time

# Script should've run, we should be invisible
# But the connections should be left!
assert aclass.namespace is not None
assert aclass_di.container is not None
assert not aclass_di.isVisible
assert aclass_di.widget.__getPyValue__() is not None
assert aclass_di.semanticModel.element == aclass
assert the_widget.canvas() is not None
assert the_widget.isVisible() == False
# BUG This should also check that child widgets
# are invisible!


########### UNDO
print "Undoing..."
coral.getTransactionManager().undo()
assert aclass.namespace is not None
assert aclass_di.container is not None
assert aclass_di.isVisible
assert aclass_di.widget.__getPyValue__() == the_widget
assert aclass_di.semanticModel.element == aclass
assert the_widget.canvas() is not None
assert the_widget.isVisible() == True

############ REDO
print "Redoing..."
coral.getTransactionManager().redo()
assert aclass.namespace is not None
assert aclass_di.container is not None
assert not aclass_di.isVisible
assert aclass_di.widget.__getPyValue__() is not None
assert aclass_di.semanticModel.element == aclass
assert the_widget.canvas() is not None
assert the_widget.isVisible() == False

m.action.quit()
