#!python

import fetchsep.opsep as opsep
import fetchsep.opsep.batch_run_opsep as batch
import fetchsep.utils.config as cfg
import argparse
import matplotlib.pyplot as plt
import datetime
from importlib import reload
import logging


############## SET DEFAULTS ##################
showplot = False
saveplot = True
detect_prev_event_default = False #Set to true if get FirstStart flag
two_peaks_default = False #Set to true if get ShortEvent flag
############## END DEFAULTS #################


parser = argparse.ArgumentParser()
parser.add_argument("--Filename", type=str, default='tmp.csv', \
        help=("Name of csv file containing list of SEP start dates and files."
        "Default is tmp.csv."))
parser.add_argument("--OutFilename", type=str, default='out.csv', \
        help=("Name of csv file containing list of SEP dates with "
            "flags indicating status after run with "
            "operational_sep_quantities.py. Default is lists/out.csv."))
parser.add_argument("--Threshold", type=str, default="",
        help=("An additional energy and flux thresholds (written as 100,1 "
                "with no spaces) which will be used to define the event. "
                "e.g. 100,1 indicates >100 MeV fluxes crossing 1 pfu "
                "(1/[cm^2 s sr]). Multiple thresholds may be written "
                "as \"30,1;50,1\" separated by a semi-colon."))
parser.add_argument("--UMASEP",
        help=("Flag to calculate flux values and thresholds specific to "
            "the UMASEP model. Thresholds for >10, >30, >50, >100 MeV and "
            "flux values at 3, 4, 5, 6, 7 hours after "
            "crossing thresholds."), action="store_true")

args = parser.parse_args()
sep_filename = args.Filename
outfname = args.OutFilename
threshold = args.Threshold
umasep = args.UMASEP

logger = logging.getLogger('opsep')

#batch.run_all_events(sep_filename, outfname, threshold, umasep)




""" Run all of the time periods and experiments in the list
    file. Extract the values of interest and compile them
    in event lists, one list per energy channel and threshold
    combination.

    INPUTS:

    :sep_filename: (string) file containing list of events
        and experiments to run
    :outfname: (string) name of a file that will report any
        errors encountered when running each event in the list
    :threshold: (string) any additional thresholds to run
        beyond >10 MeV, 10 pfu and >100 MeV, 1 pfu. Specify
        in same way as called for by operational_sep_quantities.py
    :umasep: (boolean) set to true to calculate values related to
        the UMASEP model

    OUTPUTS:

    None except for:

        * Output file listing each run and any errors encountered
        * Output files containing event lists for each unique energy
            channel and threshold combination

"""

batch.check_list_path()

#READ IN SEP DATES AND experiments
start_dates, end_dates, experiments, flux_types, flags,  \
    model_names, user_files, json_types, options, bgstart,\
    bgend = batch.read_sep_dates(sep_filename)

#Prepare output file listing events and flags
fout = open(cfg.listpath + "/opsep/" + outfname,"w+")
fout.write('#Experiment,SEP Date,Exception\n')

#---RUN ALL SEP EVENTS---
Nsep = len(start_dates)
combos = {}
print('Read in ' + str(Nsep) + ' SEP events.')
for i in range(Nsep):
    start_date = start_dates[i]
    end_date = end_dates[i]
    experiment = experiments[i]
    flux_type = flux_types[i]
    flag = flags[i]
    model_name = model_names[i]
    user_file = user_files[i]
    json_type = json_types[i]
    option = options[i]
    bgstartdate = bgstart[i]
    bgenddate = bgend[i]

    spase_id = ''

    flag = flag.split(';')
    detect_prev_event = detect_prev_event_default
    two_peaks = two_peaks_default
    doBGSub = False
    nointerp = False #if true, will not do interpolation in time
    if "DetectPreviousEvent" in flag:
        detect_prev_event = True
    if "TwoPeak" in flag:
        two_peaks = True
    if "SubtractBG" in flag:
        doBGSub = True

    print('\n-------RUNNING SEP ' + start_date + '---------')
    #CALCULATE SEP INFO AND OUTPUT RESULTS TO FILE
    try:
        sep_year, sep_month, \
        sep_day, jsonfname = opsep.run_all(start_date, end_date, experiment,
            flux_type, model_name, user_file, json_type,
            spase_id, showplot, saveplot, detect_prev_event,
            two_peaks, umasep, threshold, option, doBGSub, bgstartdate,
            bgenddate, nointerp)

        sep_date = datetime.datetime(year=sep_year, month=sep_month,
                        day=sep_day)
        if experiment == 'user' and model_name != '':
            fout.write(model_name + ',')
        if experiment != 'user':
            fout.write(experiment + ',')
        fout.write(str(sep_date) + ', ')
        fout.write('Success\n')

        #COMPILE QUANTITIES FROM ALL SEP EVENTS INTO A SINGLE LIST FOR
        #EACH THRESHOLD
        if not combos:
            combos = batch.initialize_files(jsonfname)
        success=batch.write_sep_lists(jsonfname,combos)
        if not success:
            print('Could not write values to file for ' + jsonfname)

        plt.close('all')
        opsep = reload(opsep)

    except SystemExit as e:
        # this log will include traceback
        logger.exception('opsep failed with exception')
        # this log will just include content in sys.exit
        logger.error(str(e))
        if experiment == 'user' and model_name != '':
            fout.write(model_name + ',')
        if experiment != 'user':
            fout.write(experiment + ',')
        fout.write(str(start_date) +',' + '\"' + str(e) + '\"' )
        fout.write('\n')
        opsep = reload(opsep)
        continue

fout.close()

