#!/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()
storage=m.openProject("../../../qa/models2import/Softsale.xmi")
##storage=m.openProject("someclasses.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

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)

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

action.shellSetCurrentScript("self.namespace=None")
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
#
# Made on a AMD Athlon XP 1700+, 1477 MHz
# About 1 second, let's say anything over 2 seconds sounds fishy
#
assert end_time > start_time
#This depends on what machine the test is run on and it seems to
#vary even on machines with the same hardware
#assert end_time - start_time < 2.0

# Script should've run, we should be detached
assert aclass.namespace is None
# and thus our diagram elements should also be gone
assert aclass_di.container is None
assert aclass_di.widget.__getPyValue__() is None
assert aclass_di.semanticModel.element is None

# And the widget should be gone from the canvas
assert the_widget.canvas() is None


########### UNDO
print "Undoing..."
coral.getTransactionManager().undo()
assert aclass.namespace is not None
# and thus our diagram elements should also be gone
assert aclass_di.container is not None
assert aclass_di.widget.__getPyValue__() == the_widget
assert aclass_di.semanticModel.element == aclass
assert the_widget.canvas() is not None

############ REDO
print "Redoing..."
coral.getTransactionManager().redo()
assert aclass.namespace is None
# and thus our diagram elements should also be gone
assert aclass_di.container is None
assert aclass_di.widget.__getPyValue__() is None
assert aclass_di.semanticModel.element is None
assert the_widget.canvas() is None



action.quit()
