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

import sys, string, os
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

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_createUserPanel():
    # create a Panel
    name = 'Panel_Test'
    ed.currentNetwork.createUserPanel(name)
    assert len(ed.currentNetwork.userPanels)==1, "expected 1 got %s"%len(ed.currentNetwork.userPanels)
    assert name in ed.currentNetwork.userPanels.keys(), "%s not found in userPanel.keys( %s )"%(name,ed.currentNetwork.userPanels.keys())
    pause()

def test_02_createUserPanelAndNode():
    """create a panel, add a dial and check that panel is potential master
for Dial widget"""
    name = 'Panel_Test'
    ed.createUserPanel(name)

    # add a Dial node
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)

    # open port editor
    p = node.inputPorts[0]
    p.edit()
    pause()
    values = p.objEditor.widgetMaster.get(0, 'end')
    assert name in values, "%s not listed in master combobox of port Editor (%s )"%(name,values)
    # select panel as target
    p.objEditor.widgetMaster.selectitem(name)
    # hit apply, this moves the widget to the panel
    p.objEditor.Apply()
    pause()
    widget = node.inputPorts[0].widget
    # is widget in list of widgets?
    panel = ed.currentNetwork.userPanels[name]
    assert widget in panel.widgets,\
           "Widget not in user panels.widgets. widgets are: %s"%panel.widgets
    # did the master of the widget change?
    assert widget.master == name, "Expected %s, got %s"%(name, widget.master)
    # is the Tk master correct
    assert widget.masterTk == panel.frame,\
           "Widget master is %s, Panel frame is %s"%(widget.masterTk,
                                                     panel.frame)
    

def test_03_createUserPanelAndMoveWidget():
    """create a panel, add a dial and move the dial widget to the panel and back"""
    name = 'Panel_Test'
    ed.createUserPanel(name)

    # add a Dial node
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)
    ed.currentNetwork.runOnNewData.value = True

    # open port editor
    p = node.inputPorts[0]
    p.edit()
    p.objEditor.widgetMaster.selectitem(name)
    p.objEditor.Apply()
    pause()

    # make sure the port has not become visible
    assert p.visible == False, "expected port.visible to be False got True"

    # make sure the widget is still associated with the port
    assert p.widget is not None, "expected a widget on the port, got None"
    widget = p.widget

    # check that the widget is now in the panel
    assert widget.master == name, "Widget's master is not the panel %s"%name

    # set the widget to the magic value 42.0
    widget.set(42.0)
    assert p.node.outputPorts[0].data == 42, "expected 42.0, got %s"%\
           p.node.outputPorts[0].data

    # now move the widget back to the node
    p.objEditor.widgetMaster.selectitem('Node')
    p.objEditor.Apply()
    pause()

    # check that the widget is now in the node
    widget = p.widget
    assert widget.master == 'node', \
           "Widget's master is not the node's nodeWidgetMaster"
    assert widget.inNode is True, "expected True got %s"%widget.inNode

    # set the widget to the magic value -42.0
    widget.set(-42.0)
    assert p.node.outputPorts[0].data == -42, "expected -42.0, got %s"%\
           p.node.outputPorts[0].data


def test_04_addLabelToWidgetAndMoveToPanel():
    """Test if we can add a label to a widget which did not have label
    previously, then move the widget to the user panel and the label should
    move with the widget."""
    # create user panel
    name = 'Panel_Test'
    ed.createUserPanel(name)
    # add a Dial node
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)
    pause()
    # configure the node with a new label
    widget = node.inputPorts[0].widget
    assert widget.master == 'node',"Expected 'node', got '%s'"%widget.master
    # add label
    widget.configure(labelCfg=dict(text='hello this is a test'),
                     widgetGridCfg=dict(labelSide='left') )
    assert widget.tklabel.cget('text') == "hello this is a test",\
        "Expected 'hello this is a test', got '%s'"%widget.tklabel.cget('text')
    pause()
    # now move widget to user panel
    widget.configure(master='Panel_Test')
    pause()
    # get handle to new widget, since the old one was destroyed/recreated
    widget = node.inputPorts[0].widget
    assert widget.master == 'Panel_Test',\
           "Expected 'Panel_Test', got '%s'"%widget.master
    assert widget.masterTk == ed.currentNetwork.userPanels['Panel_Test'].frame
    assert widget.tklabel.cget('text') == "hello this is a test",\
        "Expected 'hello this is a test', got '%s'"%widget.tklabel.cget('text')


def test_05_createUserPanelAndMoveWidget():
    """create a panel, add a dial and move the dial widget to the panel, save
    the network, delete, reload, and make sure the dial is still in the panel
    """
    name = 'Panel_Test'
    ed.createUserPanel(name)
    panel = ed.currentNetwork.userPanels[name]
    # add a Dial node
    node = DialNode()
    ed.currentNetwork.addNode(node, 100, 100)
    widget = node.inputPorts[0].widget
    widget.configure(master='Panel_Test')
    newwidget = node.inputPorts[0].widget
    # check that the widget is now in the panel
    assert newwidget.master == name,\
           "Widget's master is not Panel_Test but %s"%name

    assert newwidget.masterTk == panel.frame,\
           "Widget master is %s, Panel frame is %s"%(newwidget.masterTk,
                                                     panel.frame)
    # set the widget to the magic value 42.0
    newwidget.set(42.0)
    # now save the network
    # make sure there is no such file
    os.system("rm -f tmpUP_net.py*")
    # save the file
    ed.saveNetwork('tmpUP_net.py')
    # and delete the network
    ed.deleteNetwork(ed.currentNetwork)
    pause()
    # load the file
    ed.loadNetwork('tmpUP_net.py')
    pause()
    # we clean up after us...
    os.system("rm -f tmpUP_net.py*")
    assert len(ed.currentNetwork.nodes) == 1,\
           "Expected 1, got %s"%len(ed.currentNetwork.nodes)
    w = ed.currentNetwork.nodes[0].inputPorts[0].widget
    assert w.get() == 42.0,"Expected 42.0, got %s"%w.get()
    # did we re-create the user panel?
    assert ed.currentNetwork.userPanels.has_key(name),\
           "ed.userPanels is: %s"%ed.currentNetwork.userPanels
    panel = ed.currentNetwork.userPanels[name]
    # correct master?
    assert w.master == name, "Expected %s, got %s"%(name, w.master)
    assert w.masterTk == panel.frame,\
           "Widget's masterTk is not UserPanel.frame, but %s"%w.masterTk
