
# Copyright Trimble Inc 2021

#
# You'll need something like this to setup the python path:
# export PYTHONPATH=$HOME/GPSTools/pythonTools/:$HOME/GPSTools/RFPlaybackRegression/:$HOME/GPSTools/pythonTools/obstructions/
#

import numpy as np
#import io
#import os
import json
import sys
import plotOverpass as obs
import datetime
import mutils as m
#import mutils.PosTypeConst as PosTypeConst
#from ProcessResults import cdf_vals, get_rounded_cdf_percents
import matplotlib.pyplot as plt
from matplotlib import use

# Allow running headless from the command line
use("agg")

# Override pylab find() to avoid deprecation warning
# pylint: disable=function-redefined
def find(x):
  return np.where(x)[0]

if __name__ == "__main__":
  # Use the same config file as the script used to generate the data, we can 
  # use the information for labelling.
  if(len(sys.argv) == 2):
    with open(sys.argv[1],'r') as f: 
      config = json.load(f)
  else:
    print("Usage:\n  python plotTrend.py config.json")
    sys.exit()


  AllPVT = []
  for RXRec in config['RX']:
    RX = RXRec['ID']

    filename = 'Trend/RX' + str(RX) + '-Rec35_'
    if(('rec' in RXRec) and (RXRec['rec'] == '-d35:16')):
      filename += '16.csv'
    else:
      filename += '2.csv'
    PVT = np.loadtxt(filename, delimiter=",", skiprows=0)

    # Data format:
    #
    # 0 Year
    # 1 Month
    # 2 Day
    # 3 NumEpochs
    # 4 StingerEpochs
    # 5 NumOverpasses
    # 6 50%
    # 7 68%
    # 8 95%
    # 9 99%
    # 10 100%
    AllPVT.append(PVT)

  plotStr = ['50','68','95','99','100']
  for plotNum in range(6):
    for posType in range(2):
      if((posType == 1) and (plotNum == 5)):
        # No RTK yield plot needed when analyzing Stinger only solutions
        continue

      plt.figure()
      for i in range(len(config['RX'])):
        RXRec = config['RX'][i]
        RX = RXRec['ID']

        longLabel = RXRec['label'] # Too long for the title in many graphs

        if((('rec' in RXRec) and (RXRec['rec'] == '-d35:16')) or ("SBAS" in longLabel)):
          # Stinger is in loop 1
          if(posType == 0):
            continue
        else:
          # Astra / Titan is in loop 0
          if(posType == 1):
            continue

        refDate = datetime.datetime(2021,1,1)
        days =  [(datetime.datetime(int(x[0]),int(x[1]),int(x[2])) - refDate).total_seconds()/86400 for x in AllPVT[i]]
        if(plotNum == 5):
          plt.plot(days,(1.0 - AllPVT[i][:,4]/AllPVT[i][:,3])*100  ,'-1',label='RX' + str(RX) + ' - ' + longLabel)
        else:
          plt.plot(days,AllPVT[i][:,6 + plotNum],'-1',label='RX' + str(RX) + ' - ' + longLabel)

      plt.grid(True)
      plt.legend(fontsize=8)
      plt.xlabel('Time [days since 2021-01-01]')
      if(plotNum == 5):
        plt.ylabel('Precision PVT Yield [%]')
      else:
        plt.ylabel(plotStr[plotNum] + '% Error [m]')

      if(posType == 0):
        if(plotNum == 5):
          plt.title('Precision engine yield')
        else:
          plt.title('Precision (RTK) Engine (Stinger if precise not available)')
        fileStr = 'Precision'
      else:
        plt.title('Stinger Engine')
        fileStr = 'Stinger'
      plt.tight_layout()
      if(plotNum == 5):
        obs.savePlot('.','Precision-Percent-' + fileStr + '.png')
      else:
        obs.savePlot('.',plotStr[plotNum] + 'Percent-' + fileStr + '.png')
      plt.close()

