import sys
import os
import datetime

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

from numpy import *
from pylab import *

DOY  = []
Trk  = []
used = []
BM   = []
LM   = []
MM   = []
PVT  = []
LDPC = []
AJ   = []
ACQ  = []

if(len(sys.argv) != 2):
  print("Usage:\n python plotTrend.py directory")
  print("  Where directory is where the stats data is located and the output will be written")
  sys.exit(1)
else:
  localDir = sys.argv[1]
  if(not os.path.exists(localDir)):
    print("Dir " + localDir + " doesn't exist")
    sys.exit(1)


if(os.path.isfile(localDir + '/loadStinger.txt')): 

  fid = open(localDir + '/loadStinger.html','w')
  fid.write("<html><body><table border='1'>")
  fid.write("<tr><th>Date</th><th>DOY</th><th>SVs Tracked</th>")
  fid.write("<th>SVs Used</th><th>BM</th><th>LM</th>")
  fid.write("<th>MM</th><th>PVT</th><th>LDPC</th>")
  fid.write("<th>AJ</th><th>ACQ</th></tr>")

  with open(localDir + '/loadStinger.txt','r') as f:
    for line in f:
      data = line.rstrip().split()
      DOY.append( (    datetime.datetime((int)(data[0]), (int)(data[1]), (int)(data[2]), 0, 0) 
                    -  datetime.datetime(2018,1,1)).days )
      Trk.append(float(data[3]))
      used.append(float(data[4]))
      BM.append(float(data[5]))
      LM.append(float(data[6]))
      MM.append(float(data[7]))
      PVT.append(float(data[8]))
      LDPC.append(float(data[9]))
      AJ.append(float(data[10]))
      ACQ.append(float(data[11]))

      fid.write(   "<tr><td><a href='CPU_" + data[0] + data[1].zfill(2) + data[2].zfill(2) + ".Stinger.png'>"
                 + data[0] + "-" + data[1].zfill(2) + "-" + data[2].zfill(2) + "</a></td>")
      fid.write("<td>" + str(DOY[-1]) + "</td>")
      fid.write("<td>" + data[3] + "</td>")
      fid.write("<td>" + data[4] + "</td>")
      fid.write("<td>" + data[5] + "</td>")
      fid.write("<td>" + data[6] + "</td>")
      fid.write("<td>" + data[7] + "</td>")
      fid.write("<td>" + data[8] + "</td>")
      fid.write("<td>" + data[9] + "</td>")
      fid.write("<td>" + data[10] + "</td>")
      fid.write("<td>" + data[11] + "</td></tr>")
  
  fid.write("<tr><th>Date</th><th>DOY</th><th>SVs Tracked</th>")
  fid.write("<th>SVs Used</th><th>BM</th><th>LM</th>")
  fid.write("<th>MM</th><th>PVT</th><th>LDPC</th>")
  fid.write("<th>AJ</th><th>ACQ</th></tr>")
  fid.write("</table></body></html>")
  fid.close()

  fig=figure()
  ax=fig.add_subplot(111)
  plot( array(DOY), array(ACQ),'bx',  label='ACQ')
  plot( array(DOY), array(BM),'rx',   label='BM')
  plot( array(DOY), array(LM),'yx',  label='LM')
  plot( array(DOY), array(MM),'mx',   label='MM')
  plot( array(DOY), array(PVT),'cx',  label='PVT')
  plot( array(DOY), array(LDPC),'kx', label='LDPC')
  plot( array(DOY), array(AJ),'gx',   label='AJ')
  plot( array(DOY), array(Trk),'r',  label='SVs Tracked')
  plot( array(DOY), array(used),'b', label='SVs Used')
      
  xlabel('Time [Day since start of 2018]')
  ylabel('CPU Load [%]')
  grid(True)
  legend()
  tight_layout()
  # Prevent the axis numers having an offset
  ax.get_xaxis().get_major_formatter().set_useOffset(False)
  ax.get_yaxis().get_major_formatter().set_useOffset(False)
  show()
  # Save the data as a PNG file
  savefig(localDir + "/StingerTrend.png",dpi=150)
  close()

DOY  = []
Trk  = []
used = []
Stinger = []
App = []
RTK = []
Reserve = []

if(os.path.isfile(localDir + '/loadStats.txt')): 
  fid = open(localDir + '/loadStats.html','w')
  fid.write("<html><body><table border='1'>")
  fid.write("<tr><th>Date</th><th>DOY</th><th>SVs Tracked</th>")
  fid.write("<th>SVs Used</th><th>Stinger</th><th>App</th>")
  fid.write("<th>RTK</th><th>Reserve</th></tr>")

  with open(localDir + '/loadStats.txt','r') as f:
    for line in f:
      data = line.rstrip().split()
      DOY.append( (    datetime.datetime((int)(data[0]), (int)(data[1]), (int)(data[2]), 0, 0) 
                    -  datetime.datetime(2018,1,1)).days )
      Trk.append(float(data[3]))
      used.append(float(data[4]))
      Stinger.append(float(data[5]))
      App.append(float(data[6]))
      RTK.append(float(data[7]))
      Reserve.append(float(data[8]))

      fid.write(   "<tr><td><a href='CPU_" + data[0] + data[1].zfill(2) + data[2].zfill(2) + ".Loading.png'>"
                 + data[0] + "-" + data[1].zfill(2) + "-" + data[2].zfill(2) + "</a></td>")
      fid.write("<td>" + str(DOY[-1]) + "</td>")
      fid.write("<td>" + data[3] + "</td>")
      fid.write("<td>" + data[4] + "</td>")
      fid.write("<td>" + data[5] + "</td>")
      fid.write("<td>" + data[6] + "</td>")
      fid.write("<td>" + data[7] + "</td>")
      fid.write("<td>" + data[8] + "</td></tr>")
  
  fid.write("<tr><th>Date</th><th>DOY</th><th>SVs Tracked</th>")
  fid.write("<th>SVs Used</th><th>Stinger</th><th>App</th>")
  fid.write("<th>RTK</th><th>Reserve</th></tr>")
  fid.write("</table></body></html>")
  fid.close()

  fig=figure()
  ax=fig.add_subplot(111)
  plot( array(DOY), array(Stinger),'bx',  label='Stinger')
  plot( array(DOY), array(App),'rx',   label='App')
  plot( array(DOY), array(RTK),'yx',  label='RTK')
  plot( array(DOY), array(Reserve),'mx',   label='Reserve')
  plot( array(DOY), array(Trk),'r',  label='SVs Tracked')
  plot( array(DOY), array(used),'b', label='SVs Used')

  xlabel('Time [Day since start of 2018]')
  ylabel('CPU Load [%]')
  grid(True)
  legend()
  tight_layout()
  # Prevent the axis numers having an offset
  ax.get_xaxis().get_major_formatter().set_useOffset(False)
  ax.get_yaxis().get_major_formatter().set_useOffset(False)
  show()
  # Save the data as a PNG file
  savefig(localDir + "/RxTrend.png",dpi=150)
  close()
