#########################################################################
#
# Date: Aug 2004  Author: Daniel Stoffler
#
#       stoffler@scripps.edu
#
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, and TSRI
#
#########################################################################

import sys, os
from time import sleep
from Vision.VPE import VisualProgramingEnvironment
from Vision.StandardNodes import stdlib, DialNE

ed = None

###############################
## implement setUp and tearDown
###############################

def setUp():
    global ed
    ed = VisualProgramingEnvironment("test user libraries",
                                     withShell=0,
                                     visibleWidth=400, visibleHeight=300)

    ed.root.update()
    ed.configure(withThreads=0)
    ed.addLibraryInstance(stdlib, 'Vision.StandardNodes', 'stdlib')
    ed.root.update()
    

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

##########################
## Helper methods
##########################

def pause(sleepTime=0.1):
    ed.master.update()
    sleep(sleepTime)


def createUserLibrary(dirname):
    """This helper method creates a new, empty user library"""
    # delete old directory
    os.system("rm -rf ./%s"%dirname)
    # create new directory
    os.system("mkdir %s"%dirname)
    # add empty __init__.py in it
    path1 = os.path.abspath(os.path.curdir)
    path2 = os.path.join(path1, dirname)
    fullpath = os.path.join(path2, "__init__.py")
    f = open(fullpath,'w')
    f.close()
    # next, since we don't want to modify the _visionrc file, we do manually
    # what the user would have to add to this file:
    ed.addUserLibDir(path1, dirname)
    # OK! Now we are ready to create a user library! Let's show the form:
    ed.showCreateLibraryForm_cb()
    form = ed.forms['createLibsPanel']
    # Let's fill out the form:
    form.libclassnametkvar.set("testlib")
    form.libnametkvar.set("Test")
    form.libfiletkvar.set("TestNodes.py")
    form.libsGUI.setvalue(dirname)
    # set the color
    form.colorButton.configure(bg="#7A82FF")
    # now, hit the Create... button:
    form.createLib_cb()


############################################################################
## Tests
############################################################################

def test_01_createNewUserLibrary():
    """test if we can create a user library"""
    # we should have only 1 library present: the stdlib
    assert len(ed.libraries.keys()) == 1,\
           "Expected 1, got %s"%len(ed.libraries.keys())
    assert ed.libraries.has_key('Standard'),\
           "libraries.keys: %s"%ed.libraries.keys()
    # STEP1: create the directory
    dirname = "TMP_Regr_TestUserLibraryDir"
    # delete old directory
    os.system("rm -rf ./%s"%dirname)
    # create new directory
    os.system("mkdir %s"%dirname)
    # add empty __init__.py in it
    path1 = os.path.abspath(os.path.curdir)
    path2 = os.path.join(path1, dirname)
    fullpath = os.path.join(path2, "__init__.py")
    f = open(fullpath,'w')
    f.close()
    # STEP2: since we don't want to modify the _visionrc file, we do manually
    # what the user would have to add to this file:
    ed.addUserLibDir(path1, dirname)
    # STEP3: Now we are ready to create a user library! Let's show the form:
    ed.showCreateLibraryForm_cb()
    pause()
    form = ed.forms['createLibsPanel']
    # STEP4: Let's fill out the form:
    form.libclassnametkvar.set("testlib")
    pause()
    form.libnametkvar.set("Test")
    pause()
    form.libfiletkvar.set("TestNodes.py")
    pause()
    form.libsGUI.setvalue(dirname)
    pause()
    # set the color
    form.colorButton.configure(bg="#7A82FF")
    pause()
    # STEP5: now, hit the Create... button:
    form.createLib_cb()
    pause()
    # now, we should have 2 libraries present
    assert len(ed.libraries.keys()) == 2,\
           "Expected 2, got %s"%len(ed.libraries.keys())
    assert ed.libraries.has_key('Standard'),\
           "libraries.keys: %s"%ed.libraries.keys()
    assert ed.libraries.has_key('Test'),\
           "libraries.keys: %s"%ed.libraries.keys()
    # and finally, remove the directory with everything in it
    os.system("rm -rf ./%s"%dirname)

    
def test_02_addNodeToUserLibrary():
    """test if we can add a node to a user library"""
    # STEP1: create a user library
    dirname = "TMP_Regr_TestUserLibraryDir"
    createUserLibrary(dirname)
    pause()
    # STEP2: add a node to the network, modify it, select it
    net = ed.currentNetwork
    node1 = DialNE(library=stdlib)
    net.addNode(node1, 115, 60)
    node1.inputPorts[0].widget.set(23.4)
    net.selectNodes([node1])
    # STEP3: now we are ready to add this node to the libary
    # open the form:
    ed.showAddNodeToLibraryForm_cb()
    form = ed.forms['addNodeToLibsPanel']
    # STEP4: Fill out the form
    form.classNameTk.set("MyDial")
    pause()
    form.categoryNameTk.set("Output")
    pause()
    libname = "Test"
    form.libsGUI.setvalue(libname)
    pause()
    ed.master.update()
    pause(0.5)
    # STEP5: hit the Add Node... button
    form.addNode_cb()
    # OK, now the node should have been added to the library, and the selected
    # node on the network should have been replaced:
    # the library should have a new category ['Output']
    newlib = ed.libraries['Test']
    assert newlib.libraryDescr.has_key('Output'),\
           "libraries.keys: %s"%newlib.libraryDescr.keys()
    # and there should be 1 node, named MyDial
    proxys = newlib.libraryDescr['Output']['nodes']
    assert len(proxys) == 1,"Expected 1, got %s"%len(proxys)
    assert proxys[0].name == "MyDial",\
           "Expected 'MyDial', got '%s'"%proxys[0].name
    # check if the node has been added to the file
    from TMP_Regr_TestUserLibraryDir.TestNodes import testlib
    testlib.varName = newlib.varName
    testlib.modName = newlib.modName
    from TMP_Regr_TestUserLibraryDir.TestNodes import MyDial
    # now do some tests on the node on the network
    node = ed.currentNetwork.nodes[0]
    assert node.library.name == testlib.name,\
           "node.library.name: %s,  testlib.name: %s"%(
        node.library.name, testlib.name)
    assert node.inputPorts[0].widget.get() == 23.4,\
           "Expected 23.4, got %s"%node.inputPorts[0].widget.get()
    # can we instanciate the node we just imported above?
    newnode = MyDial(library=testlib)
    ed.currentNetwork.addNode(newnode, 255, 60)
    pause()
    # and finally, remove the directory with everything in it
    os.system("rm -rf ./%s"%dirname)
    pause(0.5)
