import subprocess
import pandas as pd
import sys
import os

import viewdat_cno_lib as vdl

log_cols = ['start_mdt', 'end_mdt', 'action', 'boom', 'start_utc', 'end_utc',
            'start_sec', 'end_sec', 'dt_sec', 'notes', 'no_name1', 'no_name2']

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='Make a 3D plot of T04 diagnostic FFT data.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "-F", "--folder",
        default = '240918',
        help="base directory",
    )
    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",
    )

    args = parser.parse_args()

    action_logs = get_action_logs(args.folder)

    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=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}'
        data_out_dir =  os.path.join(test_dir, 'outputs')
        os.makedirs(data_out_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]:
                txt_name = os.path.join(data_out_dir,
                                        f'{dev}_all_ant{ant}_cycle_slips.txt')
                #print(f'{txt_name=}')
                if not os.path.isfile(txt_name):
                    cmd_list = ['viewdat',
                                f'-s{start}', f'-e{end}',
                                '-i', '-c',  
                                f'--ant={ant}',
                                t04_path,
                                ]
                    print(' '.join(cmd_list) + ' > ' + txt_name)
                    f = open(txt_name, '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

        cmd_list = ['plot_slips', test_dir, '--plot_slips_max', '10100']
        print(' '.join(cmd_list))
        p = subprocess.run(cmd_list,
                           #stderr=subprocess.STDOUT, stdout=f,
                           #capture_output = True, # Python >= 3.7 only
                           #text = True # Python >= 3.7 only
        )
        #sys.exit()
