#!/usr/bin/python
#*******************************************************************************
#                                                                              *
#                                   Viewmol                                    *
#                                                                              *
#                          I M P O R T T E S T . P Y                           *
#                                                                              *
#                 Copyright (c) Joerg-R. Hill, October 2003                    *
#                                                                              *
#*******************************************************************************
#
# $Id: importtest.py,v 1.2 2004/08/29 15:21:43 jrh Exp $
# $Log: importtest.py,v $
# Revision 1.2  2004/08/29 15:21:43  jrh
# Release 2.4.1
#
# Revision 1.1  2003/11/07 13:21:14  jrh
# Initial revision
#
#

import fnmatch
import os
import sys
import string
import viewmol
import molecule
import label
try:
  from Tkinter import *
  from Tkconstants import *
  import tkMessageBox
except ImportError:
  viewmol.write('importtest.py: Tkinter or one of its components not found. Please install it before running this script again.')
  raise ImportError

class importtest:
  label1=None
  molecule=[]
  directory=None
  xPos=0
  yPos=0

  def run(self):
    viewmol.showWarnings(viewmol.__dict__['OFF'])
    self.label1=label.label()
    size=viewmol.getWindowSize()
    self.xPos=20
    self.yPos=size[1]-20
    self.label1.translate(self.xPos, self.yPos, 0)
    self.window=Tk()
    self.window.title("Turbomole/Gamess Tests")
    self.window.geometry(str(size[0]) + "x125+0+0")
    row=Frame(self.window)
    self.descriptionText=StringVar()
    description=Label(row, textvariable=self.descriptionText)
    self.descriptionText.set("Please select directory which contains test files")
    description.pack()
    row.pack()
    self.row1=Frame(self.window)
    self.dirLabel=Label(self.row1, text="Directory" + ":")
    self.dirLabel.pack(side=LEFT)
    self.directory=Entry(self.row1)
    self.directory.insert(0, os.getcwd())
    self.directory.pack(side=LEFT, expand=1, fill=X)
    self.browse=Button(self.row1, text="Browse")
    self.browse.bind("<Button>", self.browseFiles)
    self.browse.pack(side=LEFT)
    self.row1.pack(expand=1, fill=X)
    self.row2=Frame(self.window)
    self.buttonGamess=Button(self.row2, text="Run Gamess tests")
    self.buttonGamess.bind("<Button>", self.runGamess)
    self.buttonGamess.pack(side=LEFT, expand=1, fill=X)
    self.buttonTurbomole=Button(self.row2, text="Run Turbomole tests")
    self.buttonTurbomole.bind("<Button>", self.runTurbomole)
    self.buttonTurbomole.pack(side=LEFT, expand=1, fill=X)
    self.row2.pack(expand=1, fill=X)
    self.interrupt=0
    self.window.mainloop()

  def runGamess(self, event):
    path=self.directory.get()
    if os.path.isdir(path):
      self.updateDialog(path)
      files=os.listdir(path)
      if files == None:
        tkMessageBox.showerror("No Files", self.messages["error1"] + " " + path + ".")
      else:
        nfiles=0
        for file in files:
          if string.rfind(file, ".log") != -1:
	    nfiles=nfiles+1
        self.addProgressBar(nfiles)
        i=1
        for file in files:
          if string.rfind(file, ".log") != -1 and self.interrupt == 0:
            self.showFile(os.path.join(path, file), file, i, nfiles)
            i=i+1
        mol=viewmol.getMolecules()
	if len(mol) == 1:
          viewmol.delete(self.molecule[0])
    else:
      tkMessageBox.showerror("No Such Directory", "The directory " + path + " does not exist.")
    self.label1.delete()
    self.window.destroy()
    del self

  def runTurbomole(self, event):
    path=self.directory.get()
    if os.path.isdir(path):
      self.updateDialog(path)
      find=Find()
      exceptions=[]
      exceptions.append("define") # exclude the "define" tests
      exceptions.append("NumForce") # exclude the "NumForce" tests
      files=find.find("control.ref", path, exceptions)
      if files == None:
        tkMessageBox.showerror("No Files", self.messages["error2"] +" " + path + ".")
      else:
        self.addProgressBar(len(files))
        length=len(path)+1
        i=1
        for file in files:
	  if (self.interrupt == 0):
            name=file[length:]
            self.showFile(file, name, i, len(files))
            i=i+1
        viewmol.delete(self.molecule[0])
    else:
      tkMessageBox.showerror("No Such Directory", "The directory " + path + " does not exist.")
    self.label1.delete()
    self.window.destroy()
    del self

  def updateDialog(self, path):
    self.descriptionText.set("Searching for files in " + path + " ...")
    self.dirLabel.destroy()
    self.directory.destroy()
    self.browse.destroy()
    self.buttonGamess.destroy()
    self.buttonTurbomole.destroy()
    self.buttonStop=Button(self.row2, text="Stop")
    self.buttonStop.bind("<Button>", self.stop)
    self.buttonStop.pack(side=LEFT, expand=1, fill=X)
    self.window.update()

  def addProgressBar(self, nfiles):
    self.descriptionText.set("Found " + str(nfiles) + " files.")
    self.progressBar=Scale(self.row1, orient=HORIZONTAL, from_=1, to=str(nfiles))
    self.progressBar.pack(side=LEFT, expand=1, fill=X)
    self.window.update()

  def showFile(self, file, text, i, total):
    viewmol.model(viewmol.__dict__['WIREMODEL'])
    self.label1.text("Testing " + text)
    self.descriptionText.set("Testing " + text + "\n(" + str(i) + "/" + str(total) + ")")
    self.progressBar.set(i)
    self.window.update()
    try:
      viewmol.load(file)
    except ValueError:
      self.label1.text("Testing " + text + ", failed to load")
      print "Loading failed for " + text + "."
    self.molecule=viewmol.getMolecules()
    viewmol.model(viewmol.__dict__['STICKMODEL'])
    if len(self.molecule) > 1:
      viewmol.delete(self.molecule[0])
    self.molecule=viewmol.getMolecules()

  def browseFiles(self, event):
    d=DirSelectDialog(self.window, command=self.selectDirectory)
    d.popup()

  def selectDirectory(self, dir):
    if dir:
      self.directory.delete(0, len(self.directory.get()))
      self.directory.insert(0, dir)

  def stop(self, event):
    self.interrupt=1

  def register(self, language):
    viewmol.registerMenuItem("Run Gamess/Turbomole tests")

class Find:
  def find(self, pattern, dir = os.curdir, exceptions = []):
    list=[]
    names=os.listdir(dir)
    names.sort()
    for name in names:
      if name in (os.curdir, os.pardir):
        continue
      if name in exceptions:
        continue
      fullname = os.path.join(dir, name)
      if name == pattern:
        list.append(fullname)
      if os.path.isdir(fullname) and not os.path.islink(fullname):
        list = list + self.find(pattern, fullname, exceptions)
    return list

#-------------------------
if __name__ == '__main__':
  importtest().run()
