#########################################################################
#
# Date: Aug. 2003  Author: Daniel Stoffler, Michel Sanner
#
#       stoffler@scripps.edu
#       sanner@scripps.edu
#
# Copyright: Daniel Stoffler, Michel Sanner, and TSRI
#
#########################################################################

import sys, string
from NetworkEditor.simpleNE import NetworkNode
from time import sleep

from NetworkEditor.net import Network
from NetworkEditor.simpleNE import NetworkNode, NetworkBuilder
from NetworkEditor.Tests.nodes import DialNode, EvalNode

ed = None
def setUp():
    global ed
    ed = NetworkBuilder("test widgets", withShell=0,
                        visibleWidth=400, visibleHeight=300)
    ed.master.update()
    ed.configure(withThreads=0)


def tearDown():
    ed.exit_cb()
    import gc
    gc.collect()

def pause(sleepTime=None):
    if sleepTime is None:
        from NetworkEditor.Tests import pauseLength as sleepTime
    ed.master.update()
    sleep(sleepTime)


def test_01_configureDial():
    # create a dial a call configure method
    node0 = DialNode(name='Dial')
    ed.currentNetwork.addNode(node0,100,100)
    pause()
    NEwidget = node0.inputPorts[0].widget
    dial = NEwidget.widget
    # first, let's test one at a time
    cfg={'oneTurn': 3}
    apply( NEwidget.configure, (), cfg)
    assert dial.oneTurn == 3, "Expected 3, got %s"%dial.oneTurn
    cfg={'continuous':1}
    apply( NEwidget.configure, (), cfg)
    assert dial.continuous == 1, "Expected 1, got %s"%dial.continuous
    # now test the rest
    cfg = {'increment':10, 'labcfg':{}, 'lockContinuous':1, 'lockBMin':1,
           'lockBMax':1, 'lockBIncrement':1, 'lockIncrement':1, 'lockMin':1,
           'lockMax':1, 'lockOneTurn':1, 'lockPrecision':1, 'lockShowLabel':1,
           'lockType':1, 'lockValue':1,
           'min':10, 'max':20, 'oneTurn':5, 'precision':9, 'showLabel':2,
           'type':'int'}
    apply( NEwidget.configure, (), cfg)
    assert dial.increment == 10, "Expected 10, got %s"%dial.increment
    assert dial.lockContinuous == 1, "Expected 1, got %s"%dial.lockContinuous
    assert dial.lockBMin == 1, "Expected 1, got %s"%dial.lockBMin
    assert dial.lockBMax == 1, "Expected 1, got %s"%dial.lockBMax
    assert dial.lockBIncrement == 1, "Expected 1, got %s"%dial.lockBIncrement
    assert dial.lockIncrement == 1, "Expected 1, got %s"%dial.lockIncrement
    assert dial.lockMin == 1, "Expected 1, got %s"%dial.lockMin
    assert dial.lockMax == 1, "Expected 1, got %s"%dial.lockMax
    assert dial.lockOneTurn == 1, "Expected 1, got %s"%dial.lockOneTurn
    assert dial.lockPrecision == 1, "Expected 1, got %s"%dial.lockPrecision
    assert dial.lockShowLabel == 1, "Expected 1, got %s"%dial.lockShowLabel
    assert dial.lockType == 1, "Expected 1, got %s"%dial.lockType
    assert dial.lockValue == 1, "Expected 1, got %s"%dial.lockValue
    assert dial.min == 10, "Expected 10, got %s"%dial.min
    #assert dial.max == 20  # FIXME!!! THIS FAILS!!
    assert dial.oneTurn == 5, "Expected 5 got %s"%dial.oneTurn
    assert dial.precision == 9, "Expected 9, got %s"%dial.precision
    assert dial.showLabel == 2, "Expected 2, got %s"%dial.precision
    assert dial.type == int, "Expected %s, got %s"%(type(1), dial.type)
       

def test_02_setWidgetWhileHidden():
    # create an Eval node and set the value of the Entry while widget is
    # hidden
    node0 = EvalNode()
    ed.currentNetwork.addNode(node0,100,100)
    if node0.isExpanded():
        node0.toggleNodeExpand_cb()
    pause()
    w = node0.inputPorts[0].widget
    w.set('range(20)')
    node0.toggleNodeExpand_cb()
    pause()
    assert w.get()=='range(20)',"Expected 'range(20)', got %s"%w.get()
    

def test_03_setWidgetWhileShown():
    # create an Entry node and set the value of the Entry while widget is
    # shown
    node0 = EvalNode()
    ed.currentNetwork.addNode(node0,100,100)
    if not node0.isExpanded():
        node0.toggleNodeExpand_cb()
    pause()
    w = node0.inputPorts[0].widget
    w.set('range(5)')
    pause()
    assert w.get()=='range(5)',"Expected 'range(5)', got %s"%w.get()


def test_04_resizeNode():
    node0 = EvalNode()
    # hide widget if necessary
    if node0.isExpanded():
        node0.toggleNodeExpand_cb()

    ed.currentNetwork.addNode(node0,100,100)
    node0.rename('This is a really really really really long name')
    pause()
    # show widget
    node0.toggleNodeExpand_cb()
    pause()
    # hide widget
    node0.toggleNodeExpand_cb()

    # rename node
    node0.rename('abc')
    pause()
    # show widget
    node0.toggleNodeExpand_cb()
    pause()
    # hide widget
    node0.toggleNodeExpand_cb()
    pause()


def test_05_hideShowWidgetDoesNotTriggerRun():
    # node should not run when widget is hidden/shown
    # To test this, the node's compute function will increase a value which
    # would tell us then that the node has run. Which would be a bug.
    node0 = EvalNode()
    ed.currentNetwork.addNode(node0,100,100)
    ed.currentNetwork.runOnNewData.value = True
    if not node0.isExpanded():
        node0.toggleNodeExpand_cb()

    node0.private_incrData = 0 # used to store value
    outPortName = node0.outputPorts[0].name

    node0.setFunction( # add some code to the node that will increase value
      "def doit(self, in1):\n"+\
      "  self.private_incrData = self.private_incrData + 1\n"+\
      "  self.outputData("+outPortName+"=self.private_incrData)\n")
    
    w = node0.inputPorts[0].widget

    # setting the value of the widget should trigger the node to run
    w.set('range(20)')
    #private_incrData is a temporary variable, see above
    assert node0.private_incrData == 1,\
           "Expected 1, got %s"%node0.private_incrData
    pause()

    # hiding the widget should not trigger the node to run
    node0.toggleNodeExpand_cb()
    assert node0.private_incrData == 1,\
           "Expected 1, got %s"%node0.private_incrData
    pause()

    # showing the widget should not trigger the node to run
    node0.toggleNodeExpand_cb()
    assert node0.private_incrData == 1 ,\
           "Expected 1, got %s"%node0.private_incrData
    pause()

    
def test_06_refreshNetRestoresTkWidget():
    # Refresh a network destroys and rebuilds nodes and widgets
    # we test here if the widget remembers it's Tk params such as 'width'
    node0 = EvalNode()
    ed.currentNetwork.addNode(node0,100,100)
    if not node0.isExpanded():
        node0.toggleNodeExpand_cb()
    node0.inputPorts[0].widget.configure(width=12)
    wdescr = node0.inputPorts[0].widget.widgetDescr
    assert wdescr.has_key('width'),\
           "widgetDescr contains: %s"%wdescr
    assert wdescr['width'] == 12, "Expected 12, got %s"%wdescr['width']
    pause()
    # refresh network
    ed.refreshNet_cb()
    newwdescr = node0.inputPorts[0].widget.widgetDescr['width']
    assert  newwdescr== 12,\
           "Expected 12, got %s"%newwdescr
    pause()



def test_07_labelGridCfg_and_widgetGridCfg():
    """test if the labelGridCfg and widgetGridCfg were properly initialized"""
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)
    widget = node.inputPorts[0].widget
    pause()
    descr = widget.getDescr()
    # test for keys labelGridCfg and widgetGridCfg
    assert descr.has_key('labelGridCfg'),\
           "key 'labelGridCfg' is missing in %s"%descr.keys()
    assert descr.has_key('widgetGridCfg'),\
           "key 'widgetGridCfg' is missing in %s"%descr.keys()
    # test labelGridCfg
    labelGridCfg = descr['labelGridCfg']
    assert labelGridCfg.has_key('row'),\
           "key 'row' is missing in %s"%labelGridCfg.keys()
    assert labelGridCfg.has_key('column'),\
           "key 'column' is missing in %s"%labelGridCfg.keys()
    # for label, row and column should be both 0 (labelSide='left')
    assert labelGridCfg['row'] == 0,\
           "Expected row 0, got row %s for label"%labelGridCfg['row']
    assert labelGridCfg['column'] == 0,\
           "Expected column 0, got column %s for label"%labelGridCfg['column']
    # for widget, row should be 0, column should be 1
    widgetGridCfg = descr['widgetGridCfg']
    assert widgetGridCfg.has_key("row"),\
           "key 'row' is missing in %s"%widgetGridCfg
    assert widgetGridCfg.has_key("column"),\
           "key 'column' is missing in %s"%widgetGridCfg
    row = widgetGridCfg['row']
    assert row  == 0, "Expected row 0, got row %s"%row
    column = widgetGridCfg['column']
    assert row  == 0, "Expected column 0, got column %s"%column
    # no labelSide specified, so default to "left":
    assert widgetGridCfg.has_key("labelSide")
    assert widgetGridCfg['labelSide'] == 'left'
    

def test_08_addLabelLeftTopBottomRight():
    """test if we can add a label next to a widget to a node which had
    originally no label"""
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)
    widget = node.inputPorts[0].widget
    pause()
    # no label
    assert widget.tklabel.cget('text') == ''
    assert widget.labelCfg['text'] == '',\
           "Expected empty string, got %s"%widget.labelCfg['text']
    # add a label to the left side
    widget.configure(widgetGridCfg=dict(labelSide='left'),
                     labelCfg=dict(text='hello') )
    pause()
    assert widget.tklabel.cget('text') == 'hello'
    # descr updated?
    descr = widget.getDescr()
    gd = descr['widgetGridCfg']
    ld = descr['labelGridCfg']
    assert  gd['labelSide'] == 'left',\
           "Expected labelSide 'left', got %s"%gd['labelSide']
    # is it gridded correctly?
    assert ld['row'] == 0,"Expected row 0, got row %s"%ld['row']
    assert ld['column'] == 0,"Expected column 0, got column %s"%ld['column']
    assert gd['row'] == 0,"Expected row 0, got row %s"%ld['row']
    assert gd['column'] == 1,"Expected column 0, got column %s"%ld['column']

    # now grid it 'top'
     # add a label to the top
    widget.configure(widgetGridCfg=dict(labelSide='top'),
                     labelCfg=dict(text='hello') )
    pause()
    assert widget.tklabel.cget('text') == 'hello'
    # descr updated?
    descr = widget.getDescr()
    gd = descr['widgetGridCfg']
    ld = descr['labelGridCfg']
    assert  gd['labelSide'] == 'top',\
           "Expected labelSide 'top', got %s"%gd['labelSide']
    # is it gridded correctly?
    assert ld['row'] == 0,"Expected row 0, got row %s"%ld['row']
    assert ld['column'] == 1,"Expected column 0, got column %s"%ld['column']
    assert gd['row'] == 1,"Expected row 0, got row %s"%gd['row']
    assert gd['column'] == 1,"Expected column 0, got column %s"%gd['column']

    
    # now grid it 'right'
    # add a label to the right side
    widget.configure(widgetGridCfg=dict(labelSide='right'),
                     labelCfg=dict(text='hello') )
    pause()
    assert widget.tklabel.cget('text') == 'hello'
    # descr updated?
    descr = widget.getDescr()
    gd = descr['widgetGridCfg']
    ld = descr['labelGridCfg']
    assert  gd['labelSide'] == 'right',\
           "Expected labelSide 'right', got %s"%gd['labelSide']
    # is it gridded correctly?
    assert ld['row'] == 1,"Expected row 1, got row %s"%ld['row']
    assert ld['column'] == 2,"Expected column 2, got column %s"%ld['column']
    assert gd['row'] == 1,"Expected row 1, got row %s"%gd['row']
    assert gd['column'] == 1,"Expected column 1, got column %s"%gd['column']

    # now grid it 'bottom'
    # add a label to the bottom
    widget.configure(widgetGridCfg=dict(labelSide='bottom'),
                     labelCfg=dict(text='hello') )
    pause()
    assert widget.tklabel.cget('text') == 'hello'
    # descr updated?
    descr = widget.getDescr()
    gd = descr['widgetGridCfg']
    ld = descr['labelGridCfg']
    assert  gd['labelSide'] == 'bottom',\
           "Expected labelSide 'bottom', got %s"%gd['labelSide']
    # is it gridded correctly?
    assert ld['row'] == 2,"Expected row 2, got row %s"%ld['row']
    assert ld['column'] == 1,"Expected column 1, got column %s"%ld['column']
    assert gd['row'] == 1,"Expected row 1, got row %s"%gd['row']
    assert gd['column'] == 1,"Expected column 1, got column %s"%gd['column']

   
