#
# Simple script to parse XML scenarios looking for typos
#
from RunPlayback import get_config_xml, parse_XML_scenarios, getTestFileInfo
import os
import SpirentTools as ST
import xmltodict, glob

st = ST.SpirentTools(False)

if not 'sample_file_list' in globals():
    cfg = get_config_xml(st,False)
    sample_file_list, end_time_str = parse_XML_scenarios(st, cfg, None)
    file_info = getTestFileInfo( st, True )

def check_files_exist(xml_name,ref_files):
    for f in ref_files:
        if f is not None:
            if f.find('2hr230202230048.') > 0:
                continue
            if f.endswith('??.xml'):
                is_OK = False
                for i in range(16,20):
                    if os.path.isfile(f.replace('??.xml','%02d.xml'%i)):
                        is_OK = True
                        break
                if not is_OK:
                    raise RuntimeError(xml_name+' missing:'+f)
            elif os.path.isfile(f):
                #print('OK:'+f)
                pass
            else:
                raise RuntimeError(xml_name+' missing:'+f)

for info in sample_file_list:
    print(info.fileName)
    if info.RF_jam == "grid":
        print(' will jam')

    ref_files = []
    ref_files.append(info.RTK_corr_file)
    ref_files.append(info.NoPI_base)
    ref_files.append(info.NoPI_ini)
    for f in info.file_list:
        ref_files.append(f)
    ref_files.append('Samples/'+info.fileName)
    check_files_exist( info.fileName, ref_files )

def compare_scn_to_hours( xml, scn, hours ):
    from datetime import datetime
    start_time = end_time = None
    for line in open(scn,'r'):
        line = line.rstrip()
        try:
            start_time = datetime.strptime( line, '<Local Start Time> %H:%M:%S %d/%m/%y')
        except:
            pass
        try:
            end_time = datetime.strptime( line, '%H:%M:%S %d/%m/%y Local Time')
        except:
            pass
    if start_time is not None and end_time is not None:
        scn_hours = (end_time-start_time).total_seconds()/60./60.
        # trigger an error if the reported vs. scn runtime is more than 10 minutes out
        if abs(scn_hours - hours) > 10/60.:
            raise RuntimeError("Incorrect gss6450_playback/hours:\n %s\n %.2f vs %.2f"%(xml,scn_hours,hours))

for filename in sorted(glob.glob('Samples/*.xml')):
    d = xmltodict.parse(open(filename).read())['data']
    ref_files = []
    if 'gss6450_playback' in d:
        ref_files.extend(d['gss6450_playback']['file'])
        compare_scn_to_hours( filename, \
                              ref_files[0], \
                              float(d['gss6450_playback']['hours']) )
    if 'almEphClone' in d:
        ref_files.append(d['almEphClone']+'??.xml')
    if 'RTK_corr_file' in d:
        ref_files.append(d['RTK_corr_file'])
    if 'IMU_corr_file' in d:
        ref_files.append(d['IMU_corr_file'])
    if ('RTK_corr_file' in d
        and not 'IMU_corr_file' in d
        and not 'no_IMU_data' in d
        and d['type']=='Mobile'):
        print("***** Warning: missing IMU file",filename)
    if 'truth' in d and 'file' in d['truth']:
        ref_files.append(d['truth']['file'])
    check_files_exist( filename, ref_files)
    if 'regression_runs' in d:
        try:
            filename_year = filename.split('/')[-1][0:4]
            ref_year = d['set_gps_year']
            if filename_year != ref_year:
                print("set_gps_year error %s"%filename)
        except:
            print("missing set_gps_year error? %s"%filename)

        regression_runs = d['regression_runs']
        if regression_runs == 'all':
          pass
        elif regression_runs == 'none':
          pass
        else:
          # Handle formats like "week % 2 == 0"
          week = 1
          if eval(regression_runs):
            pass

print("Playback time (assuming no copy time):")
all_run_times = []
div_run_scenarios = []
div_run_times = []
for week in range(0,10):
    run_time = 0.
    for x in file_info['tests']:
        if 'regression_runs' in x:
            curr_time = x['hours']
            if x['regression_runs'] == 'none':
                continue
            elif x['regression_runs'] == 'all':
                run_time += curr_time
            elif eval(x['regression_runs']):
                run_time += curr_time
            if week == 0:
                if x['regression_runs'] == 'all':
                    all_run_times.append(curr_time)
                else:
                    div_run_scenarios.append( x['filename'])
                    div_run_times.append(curr_time)
    print(" Week %d:  %.1f hour(s)" % (week,run_time))
    if run_time > 64:
        print(" ** Warning: please try to keep below 64 hours")

# If runtimes are not evenly spaced across weeks, can use the function
# below to try and do even splits:
def divide_list_n(val,txt,n):
    a_val = []
    a_txt = []
    for i in range(n):
        a_val.append([])
        a_txt.append([])
    i_sort = argsort(-array(val))
    for i_elem in i_sort:
        elem = val[i_elem]
        elem_txt = txt[i_elem]
        i = argmin( [sum(x) for x in a_val] )
        a_val[i].append(elem)
        a_txt[i].append(elem_txt)
    for i in range(n):
        print('%.1f'%sum(a_val[i]),a_txt[i])
#divide_list_n( div_run_times, div_run_scenarios, 3 )
