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

 Interactive plot of FFT data.   Either processes
 a single T04 file or else all of the T04 files in
 a specified directory using wildcard.

   This loads rec35:25 (low-rate) or rec35:39 (high-rate)

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

  Optional arguments:
    -s, --spectrogram   Plot signal spectrogram
    -a, --auto          Autoscale plots
    -hr, --high_rate    Plot high-rate rec35:39
    -m, --plot_max      Plot max data if present
    --pngs              Save PNGs of all spectrograms
    --ant_num           Antenna number [default 0]
    --sample_point      Sample point [default 0]
    --start_time        Start time [default -1]
    --end_time          End time [default -1]

  Remember your rt_band mapping:
    band  rf_band  rt_band
     L1      0        0
     L2      1        1
     L5      6        4
     E6      7        5
     B1      8        6
     S1     10       11

  And your sample points:
     0    max7 & Auger 4-bit
     1    max8 pre-mitigation
     2    max8 post-mitigation
"""


import os
import argparse
from pylab import *
from mutils import vd2cls, plot_fft_data
from matplotlib.widgets import Slider, Button, RadioButtons


def plt_fft_data(args):

    path_name = args.path_name

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

    if args.high_rate:
        d = vd2cls(path_name, rec='-d35:39')
        print('\n Rec35:sub39 version = ' + str(int(d[0,d.k['VERSION']])) + '\n')
    else:
        d = vd2cls(path_name, rec='-d35:25')
        print('\n Rec35:sub25 version = ' + str(int(d[0,d.k['VERSION']])) + '\n')
    if args.start_time >= 0:
        d=d[d.SEC>=args.start_time]
    if args.end_time >= 0:
        d=d[d.SEC<=args.end_time]

    radio,slider,check = plot_fft_data(d,
                                       antenna_num=args.ant_num,
                                       sample_point=args.sample_point,
                                       spectrogram=args.spectrogram,
                                       plot_max=args.plot_max,
                                       autoscale=args.auto,
                                       title=path_name)

    if args.pngs and args.spectrogram:
        figure(2)
        for n in range(len(radio.labels)):
            radio.set_active(n)
            out_filename = f"{radio.value_selected}.png"
            print(f"Saving {out_filename}")
            savefig(out_filename)
    else:
        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('-s', '--spectrogram', action='store_true',
                        help='(optional) display spectrogram')
    parser.add_argument('-a', '--auto', action='store_true',
                        help='(optional) autoscale plots')
    parser.add_argument('--pngs', action='store_true',
                        help='(optional) save PNGs of all spectrograms')
    parser.add_argument('-m', '--plot_max', action='store_true',
                        help='(optional) plot max data if present')
    parser.add_argument('-hr', '--high_rate', action='store_true',
                        help='(optional) plot high-rate rec35:39')
    parser.add_argument('--ant_num', type=int, default=0,
                        help='Antenna number [default 0]')
    parser.add_argument('--sample_point', type=int, default=0,
                        help='Sample point [default 0]')
    parser.add_argument('--start_time', type=int, default=-1,
                        help='Start time [default -1]')
    parser.add_argument('--end_time', type=int, default=-1,
                        help='End time [default -1]')

    args = parser.parse_args()
    plt_fft_data(args)
