# api key from gurgle AIzaSyDDFrIPAMv3HS6PXTDcWfiUys8si_-yZ-c
import numpy as np
from gmplot import GoogleMapPlotter
from random import random
import json
from pprint import PrettyPrinter
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import FormatStrFormatter
import shutil
import requests

def rgb_to_hex(rgb):
    return '%02x%02x%02x' % rgb

def getMapImage(bbox=[38.865,-77.072,38.876,-77.001], apiKey="GKvj5HV6DLjqJT8awam4KQL3d26GP1M1", mapType="sat", mapSize=[600,400]):
    req = "https://www.mapquestapi.com/staticmap/v5/map?key={}&boundingBox={}&type={}&size={}".format(apiKey,','.join(map(str,bbox)),mapType,','.join(map(str,mapSize)))
    response = requests.get(req, stream=True)
    with open('mapImg.jpeg', 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response

def inflateBounds(bbox=[38.865,-77.072,38.876,-77.001], amt=0.001):
    return [bbox[0]-amt, bbox[1]-amt, bbox[2]+amt, bbox[3]+amt]


font = {'family' : 'DejaVu Sans',
        'weight' : 'normal',
        'size'   : 8}
matplotlib.rc('font', **font)

filenames = ["/home/llh/ros-kubernetes/plottingTools/pingStats_may_29th_2022/pingStats.json",
             "/home/llh/ros-kubernetes/plottingTools/pingStats_may_29th_2022/pingStatsDocker.json"]
# filenames = ["/home/llh/ros-kubernetes/plottingTools/pingStats_june_3rd_2022/pingStats.json",
#              "/home/llh/ros-kubernetes/plottingTools/pingStats_june_3rd_2022/pingStatsDocker.json",
#              "/home/llh/ros-kubernetes/plottingTools/pingStats_june_3rd_2022/pingStatsKubernetes.json"]
plotColors = ["orange","slateblue","mediumspringgreen"]
lats = []
longs = []
avgLatencies = []
maxAvgLatency = 0.0
realBox = [1000.0,1000.0,-1000.0,-1000.0] # (min_long, max_long, min_lat, max_lat)

# potentially the least python-ish way to handle this
for (i, fn) in enumerate(filenames):
    with open(fn) as file:
        data = json.load(file)

    # need to iterate over endpoints as well
    endpoint = "192.168.111.200"
    # ignore time stamps for now
    # and figure out center of test area
    timelessData = []
    for minuteData in data[endpoint].values():
        for pt in minuteData:
            if ("lat" in pt):
                timelessData.append(pt)

    lats.append([dataPoint["lat"] for dataPoint in timelessData])
    longs.append([dataPoint["long"] for dataPoint in timelessData])
    avgLatencies.append([dataPoint["avg"] for dataPoint in timelessData])
    maxAvgLatency = np.max(avgLatencies[i] + [maxAvgLatency])

    realBox[0] = np.min([dataPoint["lat"] for dataPoint in timelessData] + [realBox[0]])
    realBox[1] = np.min([dataPoint["long"] for dataPoint in timelessData] + [realBox[1]])
    realBox[2] = np.max([dataPoint["lat"] for dataPoint in timelessData] + [realBox[2]])
    realBox[3] = np.max([dataPoint["long"] for dataPoint in timelessData] + [realBox[3]])

print(realBox)
bigBox = inflateBounds(realBox, 0.0002)
sqrAspect = (bigBox[1] - bigBox[3])/(bigBox[0] - bigBox[2])
getMapImage(bbox=bigBox, mapType="sat", mapSize=[1000,1000])

plt.ticklabel_format(style='plain') # to prevent scientific notation
plt.ticklabel_format(useOffset=False)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))

mapPlot = plt.imread('mapImg.jpeg')
for i in range(len(lats)):
    latencySize = [50*(siz/maxAvgLatency) + 5 for siz in avgLatencies[i]]
    plt.scatter(longs[i], lats[i], zorder=1, alpha=0.8, c=plotColors[i], s=latencySize, label=[f.split('/') for f in filenames][i][-1])

plt.imshow(mapPlot, zorder=0, extent=[bigBox[1], bigBox[3], bigBox[0], bigBox[2]], aspect='equal')
plt.title('Network latency visualized')
plt.xlim(realBox[1],realBox[3])
plt.ylim(realBox[0],realBox[2])
plt.xticks(np.linspace(bigBox[1], bigBox[3], 3))
plt.yticks(np.linspace(bigBox[0], bigBox[2], 3))
plt.legend()

print(sqrAspect)
# plt.show()
plt.savefig("plottedMap.jpeg", dpi=400)
