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

 Plot RSSI & band quality data.  Either processes
 a single T04 file or else all of the T04 files
 in a specified directory using wildcard.

   This loads rec35:28

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

  Optional arguments:
    --ant_num           Antenna number [defaults to #0]
    --s_band            Also plot S-band [if present]
"""


import os
import argparse
import numpy as np
from pylab import subplots, where, log10, meshgrid, r_, show
from mutils import vd2cls, rt_band_to_label, rt_subtype_to_label


def plt_rssi_and_band_quality(args):

    path_name = args.path_name

    # Grab all T04 files in a directory
    if not path_name.endswith('.T04'):
        path_name = os.path.join(path_name, '*.T04')

    # Open a new figure window
    fig,ax = subplots(2,1,sharex=True)
    ax[0].set_title(path_name)
    ax[0].set_xlabel('GPS TOW [sec]')
    ax[0].set_ylabel('RSSI [dBm]')
    ax[1].set_xlabel('GPS TOW [sec]')
    ax[1].set_ylabel('Band Quality')

    # Load rec35:28
    d = vd2cls(path_name, rec='-d35:28')
    print('\n Rec35:sub28 version = ' + str(int(d[0,d.k['VERSION']])) + '\n')

    # Time
    t = d[:].GPS_SEC

    version = int(d[0,d.k['VERSION']])
    n_bands = int(d[0,d.k['MAX_BANDS']])
    n_subtypes = int(d[0,d.k['MAX_SUBTYPES']])

    ###################################################################
    #
    # RSSI
    #
    ###################################################################

    # Loop over RT bands
    for rt_band in range(0,12):

        # Is RSSI data supported
        if version <= 6:
            continue

        # Did we request to skip S-band
        if (rt_band == 11) and not args.s_band:
            continue

        # Dimension RSSI storage
        rssi = np.full_like(t,np.nan)

        # Loop over storage data
        for i in range(n_bands):

            # Get the RT band(s) for this entry
            rt_band_idx = d.k['RT_BAND_%2.2d' %i]

            # Get the antenna number(s) for this entry
            ant_num_idx = d.k['B_ANT_NUM_%2.2d' %i]

            # Get the RSSI values for this entry
            idx = d.k['CHANNEL_RSSI_dBm_%2.2d' %i]
            temp_rssi = d[:,idx]

            # Get indexes which match the requested band & antenna
            idx = (d[:,rt_band_idx] == rt_band) \
                & (d[:,ant_num_idx] == args.ant_num)

            # Load RSSI data
            rssi[idx] = temp_rssi[idx]

        # Channel RSSI
        if np.any(np.isfinite(rssi)):
            ax[0].plot( t, rssi, label=rt_band_to_label(rt_band) )

        ax[0].grid()
        ax[0].legend(loc='upper left')
        ax[0].set_xlim(t[0],t[-1])
        ax[0].set_ylim(-50,+5)

    ###################################################################
    #
    # Band Quality
    #
    ###################################################################

    # Loop over RT bands
    for rt_band in range(0,12):

        # Did we request to skip S-band
        if (rt_band == 11) and not args.s_band:
            continue

        # Dimension band quality storage
        qual = np.full_like(t,np.nan)

        # Loop over storage data
        for i in range(n_bands):

            # Get the RT band(s) for this entry
            rt_band_idx = d.k['RT_BAND_%2.2d' %i]

            # Get the antenna number(s) for this entry
            ant_num_idx = d.k['B_ANT_NUM_%2.2d' %i]

            # Get the band quality values for this entry
            idx = d.k['BAND_QUALITY_%2.2d' %i]
            temp_qual = d[:,idx]

            # Get indexes which match the requested band & antenna
            idx = (d[:,rt_band_idx] == rt_band) \
                & (d[:,ant_num_idx] == args.ant_num)

            # Load band quality data
            qual[idx] = temp_qual[idx]

        # Band Quality
        if np.any(np.isfinite(qual)):
            # offset the values for better legibility
            #                              |
            #                              v
            ax[1].plot( t, qual + (2-rt_band)/20,
                        label=rt_band_to_label(rt_band) )

    ax[1].grid()
    ax[1].legend(loc='upper left')
    ax[1].set_xlim(t[0],t[-1])
    ax[1].set_ylim(-0.5,+4.5)

    ###################################################################
    #
    # All done, refresh the figure window
    #
    ###################################################################

    show()


#######################################################################
#
# Command line arguments
#
#######################################################################

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('--ant_num', type=int, default=0,
                        help='antenna number [defaults to #0]')
    parser.add_argument('--s_band', action='store_true',
                        help='(optional) also plot S-band [if present]')

    args = parser.parse_args()
    plt_rssi_and_band_quality(args)

