#! /usr/bin/env python
import sys,os,time,datetime,logging
import argparse
from CalibMuon.DTCalibration.Workflow.DTCalibrationWorker import DTCalibrationWorker


log = logging.getLogger(__name__)
log_choices = [ 'ERROR', 'WARNING', 'INFO', 'DEBUG' ]
date = '%F %H:%M:%S'
log_file_name = 'dtCalibration_'
log_file_name += datetime.datetime.now().strftime( "%Y-%m-%d_%H.%M.%S" ) + '.log'

def main():
    options = parse_command_line()
    # setup logging
    setupLogging(options)

    # echo the command line used to run calibration to the log file
    log.info("DT Calibration started with command: ")
    log.info(" ".join(sys.argv))

    start = time.time()
    print "DT Calibration starting "
    print "Running at",options.working_dir

    #stdout_original = sys.stdout
    #sys.stdout = logOut

    dtCalibWorker = DTCalibrationWorker(options)
    local_path = dtCalibWorker.run()

    # move the log file to the working directory to avoid cluttering up the base directory
    print "Job dir is",local_path
    print "Log file is",log_file_name
    os.rename(log_file_name,local_path+log_file_name)

    #sys.stdout = stdout_original
    stop = time.time()
    print "DT Calibration finished"
    print "Time elapsed was %.1f seconds"%(stop-start)

def setupLogging(options):
    #setup logging
    format = '%(levelname)s (%(name)s) [%(asctime)s]: %(message)s'
    #logging.basicConfig( level=logging._levelNames[ options.debug ], format=format, datefmt=date )
    logging.basicConfig(filename=log_file_name, level=logging.DEBUG, format=format, datefmt=date )
    log.setLevel(logging._levelNames[ options.debug ])
    #formatter = logging.Formatter( format )
    #hdlr = logging.FileHandler( log_file_name, mode='w' )
    #hdlr.setFormatter( formatter )
    #log.addHandler( hdlr )
    logging.getLogger('CRAB3').propagate = False  # Avoid any CRAB message to propagate up to the handlers of the root logger.


def parse_command_line():
    ''' Setup command line options using prog command [options] sheme '''
    # This is the main parser instance. This parser will be called to parse the passed args
    descr = "Main script to perform various DT calibration tasks.\n"
    descr += "Choose a workflow, in some cases a workflow mode and a command\n"
    descr += "example dtCalibration ttrig timeboxes submit"
    main_parser = argparse.ArgumentParser(description=descr)
    main_parser.add_argument( '--debug',
        metavar='LEVEL', default='INFO',
        choices=log_choices,
        help='Set the debug level. Allowed values: ' +
            ', '.join( log_choices ) + ' [default: %(default)s]' )
    DTCalibrationWorker.add_arguments( main_parser )

    return main_parser.parse_args()


if __name__ == '__main__':
    main()
