#! /usr/bin/env python3
################################################################################
#
# Copyright (c) 2011 The MadGraph5_aMC@NLO Development team and Contributors
#
# This file is a part of the MadGraph5_aMC@NLO project, an application which 
# automatically generates Feynman diagrams and matrix elements for arbitrary
# high-energy processes in the Standard Model and beyond.
#
# It is subject to the MadGraph5_aMC@NLO license which should accompany this 
# distribution.
#
# For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch
#
################################################################################
""" This is the main script in order to generate events in MadEvent """

import logging
import logging.config
import os
import re
import shutil
import subprocess
import sys
import time
root_path = os.path.split(os.path.dirname(os.path.realpath( __file__ )))[0]
pjoin = os.path.join
sys.path.append(pjoin(root_path,'bin','internal'))
import amcatnlo_run_interface as run      

if sys.version_info < (3, 7):
    sys.exit('MadEvent works with python 3.7 or higher.\n\
               Please upgrade your version of python.')

try:
    import six
except ImportError:
    message = 'madgraph requires the six module. The easiest way to install it is to run "pip install six --user"\n'
    message += 'in case of problem with pip, you can download the file at https://pypi.org/project/six/ . It has a single python file that you just need to put inside a directory of your $PYTHONPATH environment variable.'
    sys.exit(message)

    
def set_configuration():
    import coloring_logging
    logging.config.fileConfig(os.path.join(root_path, 'bin', 'internal', 'me5_logging.conf'))
    logging.root.setLevel(logging.INFO)
    logging.getLogger('amcatnlo').setLevel(logging.INFO)
    logging.getLogger('madgraph').setLevel(logging.INFO)    


def treat_old_argument(argument):
    """Have the MG4 behavior for this script"""

    try:
        mode = int(argument[1])
    except:
        mode = int(six.moves.input('Enter 2 for multi-core, 1 for parallel, 0 for serial run\n'))
    if mode == 0:
        try:
            name = argument[2]
        except:
            name = six.moves.input('Enter run name\n')
    else:
        try:
            opt = argument[2]
        except:
            if mode == 1: 
                opt = six.moves.input('Enter name for jobs on pbs queue\n')
            else:
                opt = int(six.moves.input('Enter number of cores\n'))
        
        try:
            name = argument[3]
        except:
            name = six.moves.input('enter run name\n')

#    launch = ME.MadEventCmd(me_dir=root_path)
        

    if mode == 1:
        argument = ['fake','-f', str(name), '--cluster']
    elif mode == 2:
        argument = ['fake','-f', '--multicore', str(name), '--nb_core=%s' % opt]
    else:
        argument = ['fake','-f', name]

    return argument







################################################################################  
##   EXECUTABLE
################################################################################                                
if '__main__' == __name__:
    # Check that python version is valid

    set_configuration()
    argument = sys.argv
    try:
        if '-h' in argument or '--help' in argument:
            launch = run.aMCatNLOCmd(me_dir=root_path)
            launch.exec_cmd('help launch')
            sys.exit()
        elif len(argument) > 1 and argument[1] in ['0', '1', '2']:
            argument = treat_old_argument(argument)
        
        launch = run.aMCatNLOCmd(me_dir=root_path)
        launch.run_cmd('launch %s' % ' '.join(argument[1:]))
        launch.run_cmd('quit')
    except KeyboardInterrupt:
        try:
            launch.run_cmd('quit')
        except:
            pass
                          
    if os.path.exists(pjoin(root_path, 'RunWeb')):  
        os.remove(pjoin(root_path, 'RunWeb'))      
            
    # reconfigure path for the web 
    #if len(argument) == 5:
    #    ME.pass_in_web_mode()

             
        

        
    
    
    
    
    
    
    
