# console connection script used to link python module with shell
# JP Janet

import os, sys

import tensorflow as tf
import openbabel as ob

from ofrcalc.routines.iomanager import loadInputFile, velocityValidator   
from ofrcalc.routines.runmanager import multiRunManager
from ofrcalc.routines.inputparser import createParser


def main():
    """
    Console access point to ofrcalc.routines.runmanager,
    used to predict COF for new potential OFR molecules
    based on the a neural network trained on non-equilibrium
    molecular dynamics (NEMD). 
    
    should be called with ofrcalc <inputfile> 
    """
    
    # squelch some TF output
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    os.environ['KMP_WARNINGS'] = '0'
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
    tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
    try:
        from tensorflow.python.util import module_wrapper as deprecation
    except ImportError:
        from tensorflow.python.util import deprecation_wrapper as deprecation
    deprecation._PER_MODULE_WARNING_LIMIT = 0
   
    # squelch some OB output
    msghdlr = ob.OBMessageHandler()
    msghdlr.SetOutputLevel(0)
    
    # create input parser
    parser = createParser()
    
    # read the system args
    args = parser.parse_args()
    
    
    # if successful, check that file exits
    if not os.path.isfile(args.infile):
        print('Error: input file ' + str(args.infile) + ' does not exist')
        sys.exit(1)

    else:
        
        # get the inputs
        ins  = loadInputFile(args.infile)
        
        # create the velocity range
        vrange, valid, valErrors = velocityValidator(args)
        
        # create the job
        if valid:                
            print('sliding velocity range is from '+ str(vrange[0]) + \
            ' to ' +  str(vrange[-1]))
            # pass the inputs to the caller:
            r = multiRunManager(inputList = ins, vrange = vrange, \
                                picDir = args.picDir, \
                                resDir = args.resDir, \
                                getGradients = args.getGradients,\
                                absGradients = args.absGradients)
            # return to the shell
            sys.exit(r)

        else:
            print(valErrors)
            # return to the shell in error state
            sys.exit(1)

if __name__ == '__main__':
    main()
