import subprocess
import pandas as pd
import sys
import os
import matplotlib.pyplot as plt

action_logs = [
        'action_log_1.csv',
        'action_log_2.csv',
        'action_log_3.csv',
        'action_log_4.csv',
        'action_log_5.csv',
        'action_log_6.csv',
        'action_log_7.csv',
        ]
log_cols = ['start_mdt', 'end_mdt', 'action', 'boom', 'start_utc', 'end_utc',
            'start_sec', 'end_sec', 'dt_sec']

t04s = ['BX992_all.T04', 'EB1-5093_all.T04', 'EB1-5095_all.T04', 'P4-05_all.T04']

# Note: put them in reverse order of preference. The (reversed) order below
# *should* match the output of GNSSUtil.
svtype_sorter = [
        'MSS', 'IRNSS', 'XPS', 'OmniStar', 'QZSS', 
        'BeiDou', 'Galileo', 'GLONASS', 'SBAS', 'GPS', 
        ]
# Note: put them in reverse order of preference. The (reversed) order below
# *should* match the output of GNSSUtil.
freq_sorter = [
        'MSS', 'S1', 'XPS', 'G3', 'E1', 'B3', 'B1', 
        'E6', 'E5A+B', 'E5B/B2',
        'L5/E5A', 'L2', 'L1',
        ]

#if not os.path.isfile('per_test_sorted.csv'):
df = pd.read_csv('per_test.csv')
df['SVType'] = pd.Categorical(df['SVType'], svtype_sorter)
df['Freq'] = pd.Categorical(df['Freq'], freq_sorter)
df = df.sort_values(['SVType', 'Freq'], ascending=False).reset_index()
#    df.to_csv('per_test_sorted.csv', index=False)
#df = pd.read_csv('per_test_sorted.csv')
#print(df)

os.makedirs('per_test_figs', exist_ok=True)

devs = ['BX992', 'EB1-5093', 'EB1-5095', 'P4-05']
N_devs = len(devs)
for test in df.test.unique():
    for ant in [0, 1]:
        fig = plt.figure(figsize=(20, 8), constrained_layout=True)
        for n_dev, dev in enumerate(devs):
            print(f'   Plotting: {test=}, {ant=}, {N_devs=}, {n_dev=}, {dev=}')
            dfq = df.query(f'test=={test} and ant=={ant} and dev=="{dev}"')
            if dfq.empty:
                continue

            dft = dfq[['SVType', 'Freq', 'num_slips', 'num_obs']].copy()
            dfg = dft.groupby(['SVType', 'Freq'], sort=True, observed=True)[['num_slips', 'num_obs']].sum()
            dfg['percent_slips'] = dfg.num_slips / dfg.num_obs 

            # Num Slips
            ax = plt.subplot(3, N_devs, n_dev+1)
            dfg['num_slips'].plot(kind='barh', ax=ax)
            plt.title(f'Test {test} ant{ant} {dev}')
            plt.xlabel('number of Cycle slips')

            # Num Obs
            ax = plt.subplot(3, N_devs, N_devs+n_dev+1)
            dfg['num_obs'].plot(kind='barh', ax=ax)
            plt.xlabel('Number Observations')

            # Percent Slips
            ax = plt.subplot(3, N_devs, 2*N_devs+n_dev+1)
            dfg['percent_slips'].plot(kind='barh', ax=ax)
            plt.xlabel('percent of Cycle slips')
            ax.set_xlim([0, 0.4])
            ax.grid(True, axis='x')

        # Save
        png_fname = os.path.join('per_test_figs', f'test-{test}_ant-{ant}_num_slips.png')
        print(f'Saving {png_fname}')
        plt.savefig(png_fname)
        plt.close()

            #sys.exit()

