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

import os
import datetime
import argparse
import sys;
import json;

from pylab import *
import numpy as np

plotSymb = [ "bo", "ro", "co", "go", "ko", "yo", "mo",
             "b*", "r*", "c*", "g*", "k*", "y*", "m*"]

# Load the JSON file 
with open('receivers.json', 'r') as f:
  receivers = json.load(f)

MaxRX = len(receivers['receivers'])

# Cols
#   0 - Year
#   1 - Month
#   2 - Day
#   3 - Len
#
#   4 - mean(E)
#   5 - sig(E)
#   6 - 68% E
#   7 - 95% E
#   8 - 99% E
#   9 - 100% E
#
#  10 - 15 - repeat for N 
#  16 - 21 - repeat for U
#
#  22 - 68% 2D
#  23 - 95% 2D
#  24 - 99% 2D
#  25 - 100% 2D

# 2D velocity error
summaryFig = figure()
summaryAx = summaryFig.add_subplot(111)

for j in range(MaxRX):
  RXDir = receivers['receivers'][j]['RXDir']
  RXStr = receivers['receivers'][j]['RXStr']

  filename = RXStr + "/VelocityStats.txt"
  if(os.path.isfile(filename)): 
    #print(filename)

    vel = np.loadtxt(RXStr + "/VelocityStats.txt")
    #DOY = [print(*x.astype(int)) for x in vel[:,0:3]]
    #DOY = np.array([datetime.datetime(*x.astype(int)).timetuple().tm_yday for x in vel[:,0:3]])
    DOY = np.array([(datetime.date(*x.astype(int)) - datetime.date(2018,1,1)).days for x in vel[:,0:3]])

    # Generate an HTML table of historical results
    fid = open(RXStr + '/summary.html' ,'w')
    fid.write("<html><body>")
    fid.write("<a href='velocityTrend-68.png'>68% Trend</a>")
    fid.write("<br/>")
    fid.write("<a href='velocityTrend.png'>95% Trend</a>")
    fid.write("<table border='1'>\n")
    fid.write(  "<tr>" 
              + "<th rowspan='2'>Date</th><th rowspan='2'>2D</th><th rowspan='2'>ENU</th>"
              + "<th rowspan='2'>DOY</th>"
              + "<th colspan='3'>2D</th><th colspan='15'>ENU</th>"
              + "</tr><tr>"
              + "<th>68%</th><th>95%</th><th>100%</th>"
              + "<th>E &mu;</th><th>N &mu;</th><th>U &mu;</th>"
              + "<th>E &sigma;</th><th>N &sigma;</th><th>U &sigma;</th>"
              + "<th>E 68%</th><th>N 68%</th><th>U 68%</th>"
              + "<th>E 95%</th><th>N 95%</th><th>U 95%</th>"
              + "<th>E 100%</th><th>N 100%</th><th>U 100%</th>"
              + "</tr>\n")
    for i in range(len(DOY)):
      fid.write("<tr><td>%4d-%02d-%02d</a></td>" % 
                ( int(vel[i,0]), int(vel[i,1]), int(vel[i,2])))
      fid.write("<td><a href='%4d%02d%02d-velocity2D.png'>2D</a></td>" % 
                (  int(vel[i,0]), int(vel[i,1]), int(vel[i,2])))
      fid.write("<td><a href='%4d%02d%02d-velocity.png'>ENU</a></td>" % 
                (  int(vel[i,0]), int(vel[i,1]), int(vel[i,2])))
      fid.write("<td>%d</td>" % (DOY[i]))
      fid.write("<td>%.3f</td>" % (vel[i,22]))
      fid.write("<td>%.3f</td>" % (vel[i,23]))
      fid.write("<td>%.3f</td>" % (vel[i,25]))
      fid.write("<td>%.3f</td>" % (vel[i,4]))
      fid.write("<td>%.3f</td>" % (vel[i,10]))
      fid.write("<td>%.3f</td>" % (vel[i,16]))
      fid.write("<td>%.3f</td>" % (vel[i,5]))
      fid.write("<td>%.3f</td>" % (vel[i,11]))
      fid.write("<td>%.3f</td>" % (vel[i,17]))
      fid.write("<td>%.3f</td>" % (vel[i,6]))
      fid.write("<td>%.3f</td>" % (vel[i,12]))
      fid.write("<td>%.3f</td>" % (vel[i,18]))
      fid.write("<td>%.3f</td>" % (vel[i,7]))
      fid.write("<td>%.3f</td>" % (vel[i,13]))
      fid.write("<td>%.3f</td>" % (vel[i,19]))
      fid.write("<td>%.3f</td>" % (vel[i,9]))
      fid.write("<td>%.3f</td>" % (vel[i,15]))
      fid.write("<td>%.3f</td>" % (vel[i,21]))
      fid.write("</tr>\n")
    fid.write(  "<tr>" 
              + "<th rowspan='2'>Date</th><th rowspan='2'>2D</th><th rowspan='2'>ENU</th>"
              + "<th rowspan='2'>DOY</th>"
              + "<th>68%</th><th>95%</th><th>100%</th>"
              + "<th>E &mu;</th><th>N &mu;</th><th>U &mu;</th>"
              + "<th>E &sigma;</th><th>N &sigma;</th><th>U &sigma;</th>"
              + "<th>E 68%</th><th>N 68%</th><th>U 68%</th>"
              + "<th>E 95%</th><th>N 95%</th><th>U 95%</th>"
              + "<th>E 100%</th><th>N 100%</th><th>U 100%</th>"
              + "</tr><tr>"
              + "<th colspan='3'>2D</th><th colspan='15'>ENU</th>"
              + "</tr>\n")
    fid.write("</table></body></html>\n")
    fid.close()


    North68 = vel[:,6]
    East68  = vel[:,12]
    Up68    = vel[:,18]

    North95 = vel[:,7]
    East95  = vel[:,13]
    Up95    = vel[:,19]
    
    twoD68  = vel[:,22]
    twoD95  = vel[:,23]

    fig = figure()
    plot( DOY, East95,  label='E 95%')
    plot( DOY, North95, label='N 95%')
    plot( DOY, Up95,    label='U 95%')
    plot( DOY, twoD95,  label='2D 95%')
    ylabel('Velocity [m/s]')
    grid()
    legend()
    xlabel('Time [Day of Year]')
    title('Velocity 95% Error')
    tight_layout()
    show()
    # Save the data as a PNG file
    savefig(RXStr + "/velocityTrend.png",dpi=150)
    close()
  

    fig = figure()
    plot( DOY, East68,  label='East 68%')
    plot( DOY, North68, label='North 68%')
    plot( DOY, Up68,    label='Up 68%')
    plot( DOY, twoD68,  label='2D 95%')
    ylabel('Velocity [m/s]')
    grid()
    legend()
    xlabel('Time [Day of Year]')
    title('Velocity 68% Error')
    tight_layout()
    show()
    # Save the data as a PNG file
    savefig(RXStr + "/velocityTrend-68.png",dpi=150)
    close()

    figure(summaryFig.number)
    plot( DOY, twoD95,plotSymb[j],label=RXStr)

# Now save the plot with all data plotted together
ylabel('Velocity [m/s]')
grid()
legend()
xlabel('Time [Day of Year]')
title('2D Velocity 95% Error')
show()
tight_layout()
savefig("velocityTrendSummary.png",dpi=150)
close()



