import sys
import urllib
import time
import subprocess

# Follow specified tracking-DB target, circling at specified radius, updating 
# centroid at specified interval.


SHELF_LIFE_SEC = 120       # Don't process locations any older than this
MIN_WCS_INTERVAL_SEC = 60  # Don't call wcs faster than this 

if len(sys.argv) != 3:
    print 'usage: platform-name radius'
    exit(1)

platform = sys.argv[1]
radius = float(sys.argv[2])

print 'Average target location from past ' + str(SHELF_LIFE_SEC) + ' sec'
url = "http://odss.mbari.org/trackingdb/position/" + platform + "/last/" + \
    str(SHELF_LIFE_SEC) + "s/data.csv"

# Get last 50 records - then filter for most recent (workaround for apparent
# bug in trackingDB retrieval)
url = "http://odss.mbari.org/trackingdb/position/" + platform + "/last/10h/data.csv"

prevLat = prevLon = 0.
prevWcsCallTime = 0.

while True:
    try:
        print 'open ' + url
        f = urllib.urlopen(url)

    except IOError:
        print "Couldn't open url " + url
        exit(1)

    # First line is header
    hdr = f.readline()

    # Read records
    now = time.time()
    print 'time: ' + str(now)
    nRecs = 0
    sumLat = sumLon = 0.

    for line in f.readlines():
        fields = line.split(",")
        print 'line: ' + line
        print 'age: ' + str(now - float(fields[1]))

        if (now - float(fields[1])) > SHELF_LIFE_SEC:
            # Done with recent records
            break

        print str(fields[3]) + ", " + str(fields[2])
        sumLat += float(fields[3])
        sumLon += float(fields[2])
        nRecs += 1
        
    if nRecs == 0:
        print 'No data fresher than ' + str(SHELF_LIFE_SEC) + ' seconds old'
        time.sleep(5)
        continue

    lat = sumLat / nRecs
    lon = sumLon / nRecs
    print 'avg: ' + str(lat) + ", " + str(lon) + " (" + str(nRecs) + ")"

    if lat == prevLat and lon == prevLon:
        print 'Target location unchanged'
        time.sleep(5)
        continue

    prevLat = lat
    prevLon = lon

    arg = '%ffn.gotoWatch(' + str(lat) + ',' + str(lon) \
        + ',' + str(radius) + ')'
    
    print 'arg: ' + arg

    now = time.time()
    waitTime = MIN_WCS_INTERVAL_SEC - (now - prevWcsCallTime)
    if waitTime > 0.:
        print 'Wait ' + str(waitTime) + ' before issuing command'
        time.sleep(waitTime)

    prevWcsCallTime = now
    subprocess.call(['./wcs', arg])
    print 'Back from wcs'

exit(0)
    

