import argparse
import subprocess
import pandas as pd
import sys
import os

def get_action_logs(d='.'):
    action_logs = []
    for item in sorted(os.listdir(d)):
        if not os.path.isfile(item):
            continue
        if not item.endswith('.csv'):
            continue
        if not item.startswith('Action_Log_'):
            continue
        if item.startswith('_'):
            continue
        if item.startswith('.'):
            continue
        action_logs.append(item)
    print(f'{action_logs=}')
    return action_logs


def main():
    parser = argparse.ArgumentParser(
        description='Use t0x2t0x to split data by test #, elevation, antenna',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "-F", "--folder",
        default = '240918',
        help="base directory",
    )
    parser.add_argument(
        "-e", "--elev",
        default = 0,
        help="Elevation Mask to Use",
    )
    parser.add_argument(
        "-a", "--ant",
        default = None,
        help="Antenna to use. None for both.",
    )
    parser.add_argument(
        "--t04s",
        nargs='+',
        default = ['BX992_all.T04', 'EB1-5093_all.T04', 'EB1-5095_all.T04',
                   'EB-5081_all.T04', 'P4-05_all.T04'],
        help="list of T04 file names",
    )
    parser.add_argument(
        "--action_log_cols",
        nargs='+',
        default = ['start_mdt', 'end_mdt', 'action', 'boom', 
                   'start_utc', 'end_utc',
                   'start_sec', 'end_sec', 'dt_sec', 'notes', 'no_name1',
                   'no_name2'],
        help="list of T04 file names",
    )
    parser.add_argument(
        '-n', "--dry_run",
        action='store_true',
        help="Skip running t0x2t0x"
        )
    args = parser.parse_args()

    action_logs = get_action_logs('.')

    d_list = []
    for log in action_logs:
        test_num = int(log.split('_')[2].split('.')[0])
        print(log, test_num)
        df_log = pd.read_csv(log, names=args.action_log_cols, skiprows=6, usecols=range(0,8))
        #print(df_log)
        start = df_log.iloc[0, 6]
        end = df_log.iloc[-1, 7]
        #print(f'{log=}', start, end)
        test_dir = f'{args.folder}_{test_num}'
        if args.elev:
            test_dir = test_dir + f'_el{args.elev}'
        if args.ant:
            test_dir = test_dir + f'_ant{args.ant}'
        os.makedirs(test_dir, exist_ok=True)
        for t in args.t04s:
            t04_path = os.path.join(args.folder, t)
            dev = t.split('_')[0]
            for ant in [0, 1]:
                t04_path_out = os.path.join(test_dir, f'{dev}.T04')
                log_path = os.path.join(test_dir, 'per_test_t0x.log')
                #print(f'{t04_path_out=}')
                if not os.path.isfile(t04_path_out):
                    cmd_list = ['t0x2t0x',
                                f'-start={start}', f'-end={end}',
                                ]
                    if args.elev:
                        cmd_list = cmd_list + [f'-elev={args.elev}']
                    if args.ant:
                        cmd_list = cmd_list + [f'-a={args.ant}']
                    cmd_list = cmd_list + [t04_path, t04_path_out]
                    print(' '.join(cmd_list))

                    if not args.dry_run:
                        f = open(log_path, 'w')
                        p = subprocess.run(cmd_list,
                                           stderr=subprocess.STDOUT, stdout=f,
                                           #capture_output = True, # Python >= 3.7 only
                                           #text = True # Python >= 3.7 only
                        )
                        f.close()
                        if p.returncode != 0:
                            print(f'*** WARNING *** viewdat return code {p.returncode}')
                        #print(f'ERROR: could not find {per_test_csv_fname}')
                        #continue


if __name__ == '__main__':
    main()
