#!/usr/bin/env python

#######################################################
# Copyright Trimble Inc 2021
# Purpose: For plotting out various plots to assist with 
#          radio testing to do with increasing correction 
#          age. See TT-14373 
# Contributor(s): Joshua_McLean@Trimble.com, 
#######################################################

import argparse
import os
import sys

import matplotlib
import mutils as m
import numpy as np

#from mutils import *

parser = argparse.ArgumentParser(description='Generate .png plots for record 98 (delta times per type)')
parser.add_argument('filename', help='T0x filename')
parser.add_argument('--fig', help='Output plots in Matlab fig instead of PNG', action='store_true')
parser.add_argument('--opt', help='Extra args to pass on to Viewdat.exe. example --opt=\"-s34000 and -e35000\"', default=None, type=str)
args = parser.parse_args()

# Allow running headless from the command line
if (args.fig == False):
    matplotlib.use("agg")

if (args.opt != None):
    d=m.cmd2arr("VIEWDAT.exe -d98 -mb " + args.opt + " \"" + args.filename + "\"")
else:
    d=m.cmd2arr("VIEWDAT.exe -d98 -mb \"" + args.filename + "\"")


# parse record 98 and build the x and y values where
# x values is GPS time and y is delta time
# compared to previous record of same time
def build_xy_values_from_rec98(d, recType):
    xValues = [] # gps time
    yValues = [] 

    i = 0 # skip first

    firstGpsSecond = -1

    prevValue = 0
    while i < len(d): 

        timeMs = d[i][2]
        time = timeMs / 1000.0

        if (time > 0 and firstGpsSecond == -1):
          firstGpsSecond = time

        if (time < firstGpsSecond):
          time += 604800 #(60 * 60 * 24 * 7)

        if d[i][0] == recType:
            if prevValue != 0:            
                diff = d[i][2] - prevValue   
                if (diff > 0):         
                    xValues.append(diff)             
                    yValues.append(time) 
            prevValue = d[i][2]

        i += 1

    return xValues, yValues

# plot out record 98 for correction type if it exists
def plot_record98( d, filename, recType, label ):
    """Inputs: d,k = rec 98 in -mb format
    Use cmd2arr
    """
    xValues, yValues = build_xy_values_from_rec98(d, recType)

    if len(xValues) == 0:
        return

    fig = m.figure()
    m.plot( yValues, xValues, ".", label=label, markersize=2)


    m.title("Rec 98 Time deltas - " + label + "\n[" + os.path.basename(filename) + "]")
    m.xlabel('GPS Second')
    m.ylabel('Time deltas (milliseconds)')

    m.grid(True)
    m.legend(loc='best')
    m.tight_layout()

    if (args.fig == True):
        m.show()
    else:
        pngName = filename + '_rec98_plot_' + str(recType) + '.png'
        m.savefig(pngName)
        print('saved %s' % pngName)

        #create zoomed plot if needed
        yMin, yMax = fig.gca().get_ylim()
        if yMax > 20000 :
            fig.gca().set_ylim(0, 10000) #20s
            pngName = filename + '_rec98_plot_' + str(recType) + '_zoom.png'
            m.savefig(pngName)
            print('saved %s' % pngName)
    

    return


# plot out delta times from record 98
plot_record98( d, args.filename, 128, "Cmr (128)")      #cmr    
plot_record98( d, args.filename, 129, "Rtcm (129)")     #rtcm   
plot_record98( d, args.filename, 130, "Rtcm3 (130)")    #rtcm32 
plot_record98( d, args.filename, 131, "CmrxRaw (131)")  #rtx / xfill
