import collections,math,sys
# Scan the cctv file to find the nearest vds
# This is a one-time job to create the static file of cctv locations and nearest vds
# The output of this program needs to be manually modified before input to cptms_map.html
# 1. The vds column is appended to cctvFile (yes, adding a new column to the original input).
# 2. Convert this csv file to json (using cctvToJson.awk)
# 3. Remove tabs from json.  Trim any blanks from nearVDS field. 
# jdalbey Mar 2019
vdsFile = "vds_fromhighwaysmap.csv"
cctvFile = "cctv_locations_D12.csv"
orientationLookup = {'N':0,'S':1,'E':0,'W':1}

def loadHighways():

    f = open(vdsFile,'r')
    lines = [line.split(',') for line in f.readlines()]
    # 5,N,0.65,4 S. LUIS REY
    # Create a set containing just the route numbers 
    routeNums = set()
    for item in lines:
        routeNums.add(int(item[0]))
    # put the route numbers in order
    sortedRoutes = sorted (routeNums)    
    # Create the empty postmile collections
    for route in sortedRoutes:
        #print route,
        highways[str(route)]=[collections.OrderedDict(),collections.OrderedDict()]
    #print
    # Process all the data, placing it in proper route and collection
    for item in lines:
        route = item[0]
        orientation = orientationLookup[item[1]]
        postmileItem = item[2]
        highways[route][orientation][postmileItem]=item


def dumpHighways():
    # Dump the highways data we've organized
    for item in highways:
        for cnt in [0,1]:
            list1 = highways[item][cnt]
            print "highway",item,list1
            # show fields for one entry
            for pm_entry in list1:
                print pm_entry,list1[pm_entry]

def findNearest():

    f = open(cctvFile,'r')
    #5,S,42.11,-117.978854,33.856288,SB 5 N/O MAGNOLIA AVE (S/O 91),12-005-CCTV-0001
    lines = [line.split(',') for line in f.readlines()]

    # Find he nearest VDS to each cctv
    for item in lines:
        route = item[0]
        orientation = orientationLookup[item[1]]
        postmileItem = item[2]
        segment = highways[route][orientation] 

        # Now we know which highway segment the cctv is on, look at all those VDS to find nearest
        print route,item[1],postmileItem+",",
        min = 9999
        nearVDS = 0
        for vds in segment:
            diff = abs(float(vds) - float(postmileItem))
            #print vds + "("+str(diff)+")",
            if (diff < min):
                min = diff
                nearVDS = vds
        print route,item[1],nearVDS

# ------------------------------------------------------------------------------------------

highways = collections.OrderedDict()    
loadHighways()
dumpHighways()
print "CCTV\tnearestVDS"
findNearest()

