# -*- coding: utf-8 -*-
#
# ccwatcher (http://ccwatcher.sourceforge.net/)
# Copyright (C) 2009-2013 Xaver Wurzenberger <xaverxn at users.sourceforge.net>
#
# This program is free software; you can redistribute and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

import StringIO 
import os 
import ccw_parser,ccw_settingshandler
import unittest
from tempfile import mkstemp


class mimicFile(StringIO.StringIO):
    """
    This class mimics a file good enough to test ccwatchers intestines.
    """


    def __init__(self, filetype):

        self.size = 0

	if filetype == 'Turbomole':
            pass#create gradient file and GEO_OPT_FAILED

        else:
            self.filedes, self.tempfile = mkstemp()
            self.filehandle = open(tempfile, 'w')  #maybe use the same energy for all to allow easier checks?

    	    if filetype == 'ADF':
                self.filehandle.write("Amsterdam Density Functional")
		self.filehandle.write(" ==========================")
		self.filehandle.write(" Geometry Convergence Tests")
		self.filehandle.write(" ==========================")
                self.filehandle.write(" \n")
                self.filehandle.write(" Energy  old :          0.00000000")
                self.filehandle.write("         new :         -0.09385878")
                self.filehandle.write(" \n")
		self.filehandle.write(" ==========================")
		self.filehandle.write(" Geometry Convergence Tests")
		self.filehandle.write(" ==========================")
                self.filehandle.write(" \n")
                self.filehandle.write(" Energy  old :         -0.09385878")
                self.filehandle.write("         new :         -0.09485878")
                self.filehandle.write(" \n")


	    if filetype == 'GAMESS_US':
                self.filehandle.write("GAMESS VERSION")
                self.filehandle.write(" FINAL R-B3LYP ENERGY IS     -382.0446773465 AFTER  17 ITERATIONS")
                self.filehandle.write(" FINAL R-B3LYP ENERGY IS     -382.0456773465 AFTER  20 ITERATIONS")

	    if filetype == 'Gaussian':
	        self.filehandle.write("Gaussian, Inc.")
                self.filehandle.write(" SCF Done:  E(UB+HF-LYP) =  -420.805187737     a.u. after    8 cycles")
                self.filehandle.write(" SCF Done:  E(UB+HF-LYP) =  -420.809187737     a.u. after    10 cycles")

            if filetype == 'Jaguar':
                self.filehandle.write("Jaguar")
                self.filehandle.write(" SCFE: SCF energy: DFT      -382.29428818504 hartrees   iterations:   7")
                self.filehandle.write(" SCFE: SCF energy: DFT      -382.29528818504 hartrees   iterations:   9")
                        
	    if filetype == 'Molpro':
                self.filehandle.write("PROGRAM SYSTEM MOLPRO")
                self.filehandle.write(" !RHF STATE 1.1 ENERGY               -429.359518480727")
                self.filehandle.write(" !RHF STATE 1.1 ENERGY               -429.359718480727")

	    if filetype == 'NWChem':
                self.filehandle.write("Northwest Computational Chemistry Package")
                self.filehandle.write("Total energy =    -379.613357")
                self.filehandle.write("Total energy =    -379.623357")

	    if filetype == 'ORCA':
                self.filehandle.write("* O   R   C   A *")
                self.filehandle.write("Total Energy       :        -1723.46835769 Eh          -46897.95826 eV")
                self.filehandle.write("Total Energy       :        -1723.46935769 Eh          -46897.95826 eV")

#                zip: import zipfile
#                ".gz", ".bz2": fileinput


    def __del__(self):
        """Remove temporary files."""
        try:
            for entry in self.list_filedes:
	        os.close(entry)
            for entry in self.list_datafiles:
	        os.remove(entry)
        except:
	    pass




def createmimicfiles(filetype,tmpfile):

    if filetype == 'Turbomole':
        pass#create gradient file and GEO_OPT_FAILED
    
    elif filetype == 'ADF':
        tmpfile.write("Amsterdam Density Functional \n")
	tmpfile.write(" ========================== \n")
	tmpfile.write(" Geometry Convergence Tests \n")
	tmpfile.write(" ========================== \n")
        tmpfile.write(" \n")
        tmpfile.write(" Energy  old :          0.00000000 \n")
        tmpfile.write("         new :         -0.09385878 \n")
        tmpfile.write(" \n")
	tmpfile.write(" ========================== \n")
	tmpfile.write(" Geometry Convergence Tests \n")
	tmpfile.write(" ========================== \n")
        tmpfile.write(" \n")
        tmpfile.write(" Energy  old :         -0.09385878 \n")
        tmpfile.write("         new :         -0.09485878 \n")
        tmpfile.write(" \n")


    elif filetype == 'GAMESS_US':
        tempfile.write("GAMESS VERSION")
        tempfile.write(" FINAL R-B3LYP ENERGY IS     -382.0446773465 AFTER  17 ITERATIONS")
        tempfile.write(" FINAL R-B3LYP ENERGY IS     -382.0456773465 AFTER  20 ITERATIONS")

    elif filetype == 'Gaussian':
        tempfile.write("Gaussian, Inc.")
        tempfile.write(" SCF Done:  E(UB+HF-LYP) =  -420.805187737     a.u. after    8 cycles")
        tempfile.write(" SCF Done:  E(UB+HF-LYP) =  -420.809187737     a.u. after    10 cycles")

    elif filetype == 'Jaguar':
        tempfile.write("Jaguar")
        tempfile.write(" SCFE: SCF energy: DFT      -382.29428818504 hartrees   iterations:   7")
        tempfile.write(" SCFE: SCF energy: DFT      -382.29528818504 hartrees   iterations:   9")
                
    elif filetype == 'Molpro':
        tempfile.write("PROGRAM SYSTEM MOLPRO")
        tempfile.write(" !RHF STATE 1.1 ENERGY               -429.359518480727")
        tempfile.write(" !RHF STATE 1.1 ENERGY               -429.359718480727")

    elif filetype == 'NWChem':
        tempfile.write("Northwest Computational Chemistry Package")
        tempfile.write("Total energy =    -379.613357")
        tempfile.write("Total energy =    -379.623357")

    elif filetype == 'ORCA':
        tempfile.write("* O   R   C   A *")
        tempfile.write("Total Energy       :        -1723.46835769 Eh          -46897.95826 eV")
        tempfile.write("Total Energy       :        -1723.46935769 Eh          -46897.95826 eV")

#                zip: import zipfile
#                ".gz", ".bz2": fileinput

#The fake file needs to provide the following:
# os.path.basename, os.path.exists, open, os.path.getmtime, os.path.getsize
#as the creation os os.stat(file).st_size is very occult, maybe its better to create a temp file

#    
class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
#        self.seq = range(10) #instead of this, setup the mimicFile
#        instance_testfiles = mimicFiles()
        self.parser = ccw_parser.fileParser(ccw_settingshandler.readSettings(ccw_settingshandler.getSettingsFileLocation()))

    def test_mimicfiles(self):
         for filetype in ['ADF']:#,'Turbomole','Gaussian']:
            filedes, tempfile = mkstemp()
	    filehandle = open(tempfile, 'w')  #maybe use the same energy for all to allow easier checks?
            createmimicfiles(filetype,filehandle)
	    filehandle.close()
            self.parser.setInputFiles((tempfile,))
   	    self.parser.parse()
	    os.close(filedes)
	    os.remove(tempfile)

#     def test_realfiles()
#	list_files = ['../..testfiles/1.log','../../testfiles/2.log'
#	for file in list_files: 
#            open(file,'r')
#        ccw_parser.setInputFiles(list_files)
#        ccw_parser.parse()

#    def test_shuffle(self):
#        self.assertEqual(self.seq, range(10))
#        self.assertRaises(TypeError, random.shuffle, (1,2,3))
#
#    def test_choice(self):
#        self.assertTrue(element in self.seq)
#
#    def test_sample(self):
#        with self.assertRaises(ValueError):
#	    pass
#            #random.sample(self.seq, 20)
#        for element in range(10):
#            self.assertTrue(element in self.seq)



def run_tests():
    mysuite = unittest.TestSuite()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
    unittest.TextTestRunner(verbosity=2).run(suite)                              #   mysuite += TestCase

    #test ccw_parser only
    #for every filetype read 2 scf values, 8*2(x+y) scalemode values
    #test zip, gz, bz2 filetypes (how?)
    #doctest?


if __name__ == '__main__':
    run_tests()
#    unittest.main()
#or:    suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
#    unittest.TextTestRunner(verbosity=2).run(suite)
