import collections,math,sys
# Scan the cctv file to find the nearest vds
# jdalbey Mar 2019
postmileFile = "d12_vds_uniq_sorted.csv"
cctvFile = "cctv_locations_D12.csv"
orientationLookup = {'N':0,'S':1,'E':0,'W':1}

def loadHighways():

    f = open(postmileFile,'r')
    lines = [line.split(',') for line in f.readlines()]
    
    # 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')
    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()
print "CCTV\tnearestVDS"
findNearest()

