#
##Copyright University of Reims Champagne-Ardenne
#Authors and Contributors: Corentin LEFEBVRE, Johanna KLEIN, Emmanuel PLUOT,
#                          Gaetan RUBEZ, Hassan KHARTABIL,
#                          Jean-Charles BOISSON and Eric HENON
#(24/07/2017)
##jean-charles.boisson@univ-reims.fr, eric.henon@univ-reims.fr
#
##This software is a computer program whose purpose is to 
#detect and prepare the plot of molecular interactions
#from electron density and IGM reference using promolecular
#electron density.
#
##This software is governed by the CeCILL-C license under French law and
#abiding by the rules of distribution of free software.  You can  use, 
#modify and/ or redistribute the software under the terms of the CeCILL-C
#license as circulated by CEA, CNRS and INRIA at the following URL
#"http://www.cecill.info". 
#
##As a counterpart to the access to the source code and  rights to copy,
#modify and redistribute granted by the license, users are provided only
#with a limited warranty  and the software's author,  the holder of the
#economic rights,  and the successive licensors  have only  limited
#liability. 
#
##In this respect, the user's attention is drawn to the risks associated
#with loading,  using,  modifying and/or developing or reproducing the
#software by the user in light of its specific status of free software,
#that may mean  that it is complicated to manipulate,  and  that  also
#therefore means  that it is reserved for developers  and  experienced
#professionals having in-depth computer knowledge. Users are therefore
#encouraged to load and test the software's suitability as regards their
#requirements in conditions enabling the security of their systems and/or 
#data to be ensured and,  more generally, to use and operate it in the 
#same conditions as regards security. 
#
##The fact that you are presently reading this means that you have had
#knowledge of the CeCILL-C license and that you accept its terms.
from __future__ import print_function
from sys import exit, version_info
from os import listdir, chdir, getcwd
from os.path import isdir, isfile, join, abspath
from argparse import ArgumentParser

import subprocess

def manageArguments():
    """ Function which parses command line arguments

    Returns:
        ArgumentParser: the objet which has validated all the command line argument
    """
    parser = ArgumentParser()
    parser.add_argument("executable", help="Path (relative or absolute) to IGMPLOT command (allow to test different versions)")
    parser.add_argument("directory",  help="Directory that contains all the sample of IGMPLOT")

    return parser.parse_args()

def test_samples(executable, directory):
    """ Tool procedure which tests all the IGMPLOT samples it finds.

    Args:
        executable (str): full path to the IGMPLOT executable
        directory (str): path (relative or absolute) to the sample directory
    """
    
    output_file_log="test_output.log"
    
    original_directory = getcwd()
    
    chdir(directory)
    
    command = [executable, 'param.igm']

    for file_name in sorted(listdir('.')):
        
        if isdir(file_name):
            path = join(getcwd(),file_name)
            
            test_samples(executable,path)
 
            
    if 'param.igm' in listdir('.'):
        
        print(getcwd(), end=' ')
        
        error_flag = False
        
        if version_info[0] < 3:
        
            try:
                run_log=subprocess.check_output([ command[0], command[1] ],stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as cpe:
                error_flag=True
                run_log=cpe.output
        else:        
       
            result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            run_log = result.stdout.decode('utf-8')
            
            error_flag = result.returncode!=0
            
        file=open(output_file_log,"w")
        file.write(run_log)
        file.close()
      
        if not error_flag:
            print('OK')
        else:
            print('KO see', output_file_log)
                    
    chdir(original_directory)
 
if __name__ == "__main__":
    
    arguments = manageArguments()
    
    if not isfile(arguments.executable):
        print('{} does not exist'.format(arguments.executable))
        exit(10)
    
    if not isdir(arguments.directory):
        print('{} is not a valid directory'.format(arguments.directory))
        exit(20)
    
    test_samples(abspath(arguments.executable), arguments.directory)

    exit(0)
