#!/usr/bin/env python

#######################################################
# Copyright Trimble Inc 2021
# Purpose: To have a quick way to plot out CPU plots from Rec 35:258 and 35:259
# 
# Plots:
# - CPU reserves

# Contributor(s): Joshua_McLean@Trimble.com, 
#######################################################

import argparse
import os
import sys

import matplotlib
import mutils as m
import numpy as np

from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
                               AutoMinorLocator)

#from mutils import *

parser = argparse.ArgumentParser(description='Generate plots for record 35:258 and 35:259 (CPU data)')
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\"', required=False, default=None, type=str)
parser.add_argument('--label', help='Plot sub label override. If none is specified, the file name is used', required=False, 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):
    info = m.parse_load_diags("\"" + args.filename + "\"", opt=[args.opt])
else:
    info = m.parse_load_diags("\"" + args.filename + "\"")


plotSubLabel = args.label
if (plotSubLabel == None):
    plotSubLabel = os.path.basename(args.filename)


#Helper fuction that does three things:
# - if args.fig is True, show the plots using Matlab UI
# - if args.inc contains a list, check if this plot included in the filter list
# - output the current fig as png
def outputOrVisiualizeCurrentFig(prefix):
    
    if (args.fig == True):
        m.show()
        return

    pngName = '%s_rec35-258_%s.png' % (args.filename, prefix)

    m.savefig(pngName)
    print('saved %s' % pngName)



##########################################
## CPU reserve  
##########################################
    
avg0 = np.nanmean(info.RESERVE)
min0 = np.nanmin(info.RESERVE)
max0 = np.nanmax(info.RESERVE)
low0 = np.nanpercentile(info.RESERVE, 10)
high0 = np.nanpercentile(info.RESERVE, 90)

fig = m.figure()
ax = fig.add_subplot(1, 1, 1)
m.plot( info.TIME, info.RESERVE, ".", markersize=2, label="CPU RESERVE (min: %0.0f, low: %.0f, avg: %.0f, high: %.0f, max: %0.0f)" % (min0, low0, avg0, high0, max0))

if ('RESERVECPU1' in info and len(info.RESERVECPU1) > 0):
  avg1 = np.nanmean(info.RESERVECPU1)
  m.plot( info.TIME, info.RESERVECPU1, ".", markersize=2, label="CPU 1 RESERVE (avg = %.0f)" % avg1)

if ('RESERVECPU2' in info  and len(info.RESERVECPU2) > 0):  
  avg2 = np.nanmean(info.RESERVECPU2)
  m.plot( info.TIME, info.RESERVECPU2, ".", markersize=2, label="CPU 2 RESERVE (avg = %.0f)" % avg2)

if ('RESERVECPU3' in info and len(info.RESERVECPU3) > 0):  
  avg3 = np.nanmean(info.RESERVECPU3)
  m.plot( info.TIME, info.RESERVECPU3, ".", markersize=2, label="CPU 3 RESERVE (avg = %.0f)" % avg3)

m.title("Rec 35:258 CPU Reserve\n[" + plotSubLabel + "]")
m.xlabel('GPS Second')
m.ylabel('CPU Reserve')
m.grid(True)
m.legend(loc='best')
m.tight_layout()

ax.yaxis.grid(True, which='minor', linestyle=':', color='lightgrey')
ax.yaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_major_formatter(FormatStrFormatter("%d"))
ax.yaxis.set_minor_locator(MultipleLocator(5))

fig.gca().set_ylim(-1, 100)

outputOrVisiualizeCurrentFig('cpu_reserves')
