#!/usr/bin/env python
"""

 Plot SNR data from master sub-channel.   Either
 processes a single T04 file or else all of the
 T04 files in a specified directory using wildcard.

   This loads rec35:19

 Example:
  ./plt_snr_data.py /home/ddelore/DataDir/RX6-2209

  Optional arguments:
    --sat_type      Satellite type [defaults to #0]
    --trk_band      Tracking band  [defaults to #0]
    --trk_type      Tracking type  [defaults to #0]
    --ant_num       Antenna number [defaults to #0]
    --elev_mask     Elevation mask [defaults to  0]

  See SV Freq/Signal Combos here:
    https://wiki.eng.trimble.com/index.php/SV_Freq/Signal_Combo

    Signal               Sat Type   Track Band   Track Type
  ---------------        --------   ----------   ----------
  GPS     L1 C/A            0           0            0
  GPS     L2C CMCL          0           1            5
  GPS     L5 IQ             0           2 (4)        8
  Galileo E1 MBOC DP        3           0           23
  Galileo E5 Alt DP         3           4           14
  Galileo E6 DP             3           5           38
  Glonass G1C               2           0            0
  Glonass G2C               2           1            0
  Glonass G3 DP             2           9 (5)       32
                                           |
                                           |
                          when the "tracking" RT band is
                         different than the "RF" RT band,
                        then the number in parentheses is
                       the RT band for regular bookkeeping
"""


import os
import argparse
import numpy as np
from pylab import unique, subplots, show
from mutils import vd2cls


def plt_snr_data(args):

    path_name = args.path_name

    if not path_name.endswith('.T04'):
        path_name = os.path.join(path_name, '*.T04')

    d = vd2cls(path_name, rec='-d35:19')
    print('\n Loaded Rec35:19\n')

    # Create a vector of unique time points
    t_unique = np.unique(d.TIME)

    # Dimension storage
    cno_tot = np.full_like(t_unique, 0)
    n_sats = np.full_like(t_unique, 0)

    # Which satellite/constellation combinations
    sv_clist = unique(d.SV + 1000*d.SAT_TYPE)
    sv_list = [(int(x) % 1000, int(x/1000)) for x in sv_clist]
    #           \           /  \         /
    #            -----------    ---------
    #                |              |
    #              sv_id         sat_type

    # Open a new figure window
    fig, ax = subplots(2,1,height_ratios=[2,1],sharex=True)
    ax[0].set_title(path_name)
    ax[0].set_xlabel('GPS TOW [sec]')
    ax[0].set_ylabel('C/N0 [dB-Hz]')
    ax[1].set_xlabel('GPS TOW [sec]')
    ax[1].set_ylabel('Number of SVs')

    for sv, sat_type in sv_list:
        if sat_type == args.sat_type:
            idx = (d.SV == sv) \
                & (d.SAT_TYPE == sat_type) \
                & (d.FREQ == args.trk_band) \
                & (d.TRACK == args.trk_type) \
                & (d.ANTENNA == args.ant_num) \
                & (d.EL >= args.elev_mask )
            t = d[idx].TIME
            cno = d[idx].CNO
            ax[0].plot(t, cno, 'o', markersize=2)

            _, _, idx = np.intersect1d(t, t_unique, return_indices=True)
            cno_tot[idx] += cno
            n_sats[idx] += 1

    ax[0].grid(True)
    ax[0].set_xlim(t_unique[0], t_unique[-1])
    ax[0].set_ylim(min(20, ax[0].get_ylim()[0]),
                   max(55, ax[0].get_ylim()[1]))

    ax[1].plot(t_unique, n_sats, 'bo', markersize=2)

    ax[1].grid(True)
    ax[1].set_xlim(t_unique[0], t_unique[-1])
    ax[1].set_ylim(0, max(15, ax[1].get_ylim()[1]))

    # Open a new figure window
    fig, ax = subplots(2,1,height_ratios=[2,1],sharex=True)
    ax[0].set_title(path_name)
    ax[0].set_xlabel('GPS TOW [sec]')
    ax[0].set_ylabel('Average C/N0 [dB-Hz]')
    ax[1].set_xlabel('GPS TOW [sec]')
    ax[1].set_ylabel('Number of SVs')

    idx = (n_sats != 0)
    t = t_unique[idx]
    cno_avg = cno_tot[idx]/n_sats[idx]

    ax[0].plot(t, cno_avg, 'bo', markersize=2)

    ax[0].grid(True)
    ax[0].set_xlim(t_unique[0], t_unique[-1])
    ax[0].set_ylim(min(20, ax[0].get_ylim()[0]),
                   max(55, ax[0].get_ylim()[1]))

    ax[1].plot(t_unique, n_sats, 'bo', markersize=2)

    ax[1].grid(True)
    ax[1].set_xlim(t_unique[0], t_unique[-1])
    ax[1].set_ylim(0, 15)

    show()


if __name__ == '__main__':
    parser = argparse \
        .ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                        description=__doc__)

    parser.add_argument('path_name',
                        help='name of or path to your T04 file(s)')
    parser.add_argument('--sat_type', type=int, default=0,
                        help='Satellite type [defaults to #0]')
    parser.add_argument('--trk_band', type=int, default=0,
                        help='Tracking band [defaults to #0]')
    parser.add_argument('--trk_type', type=int, default=0,
                        help='Tracking type [defaults to #0]')
    parser.add_argument('--ant_num', type=int, default=0,
                        help='Antenna number [defaults to #0]')
    parser.add_argument('--elev_mask', type=int, default=-999,
                        help='Elevation mask [defaults to 0]')

    args = parser.parse_args()
    plt_snr_data(args)

