# Simple script to find the closest DME stations to the
# provided positon. Data is only available for North America
import geopy.distance
import argparse
import numpy as np
import pandas as pd

######################################################################
# Parse arguments
parser = argparse.ArgumentParser(description='Finds DME Stations')
parser.add_argument('-r','--range', help='range in km to consider (default 200km) e.g. --range 200')
parser.add_argument('-p','--pos', help='Lat/long in degrees (default Sunnyvale) e.g. --pos lat,lon')
args = parser.parse_args()
######################################################################

if(args.pos):
  LatLon = args.pos.split(",")
  refLat = float(LatLon[0])
  refLon = float(LatLon[1])
else:
  refLat = 37.384901605
  refLon = -122.005482591
ref = (refLat,refLon)

if(args.range):
  rangeThres = float(args.range)
else:
  rangeThres = 200.0

# Load the DME file
DME = np.loadtxt('DMEData.csv',dtype='str',delimiter=',')

string = []
dist   = []
for i in range(len(DME)):
  lat = float(DME[i][59])
  lon = float(DME[i][60])
  station = (lat,lon)
  distance = geopy.distance.vincenty(ref, station).km

  # Find any stations less than the threshold
  if(distance < rangeThres):
    dist.append(distance)
    string.append(   "Distance = " + str.format('{0:6.2f}',distance) + "km"
           + "  station = " + DME[i][0] + " / " + str.format('{0:14}',DME[i][4])
           + "  lat = " + str.format('{0:6.3f}',float(DME[i][59]))
           + "  lon = " + str.format('{0:8.3f}',float(DME[i][60]))
           + "  DME Freq = " + str.format('{:>4}',DME[i][68]) + " MHz")

# Use pandas to generate a sorted list of stations based on distance
data = pd.DataFrame({'dist':dist, 'string':string})
sortedData = (data.sort_values('dist'))
dataList = sortedData['string'].tolist()

print("Reference Lat = %.6f Lon = %.6f" % (refLat,refLon))
print("Distance Threshold = %.0f km" % rangeThres)
print("Num Found = %d" %len(dataList))

for i in range(len(dataList)):
  print(dataList[i])



