#!/usr/bin/python
import subprocess
import httplib, urllib
import json
from gps import *
import time
import threading
import math
import dnet
import csv

class GpsController(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
        self.running = False
    
    def run(self):
        self.running = True
        while self.running:
            # grab EACH set of gpsd info to clear the buffer
            self.gpsd.next()

    def stopController(self):
        self.running = False
  
    @property
    def fix(self):
        return self.gpsd.fix

    @property
    def utc(self):
        return self.gpsd.utc

    @property
    def satellites(self):
        return self.gpsd.satellites


#hard code network information for now...
if __name__ == '__main__':
    while True:

        # create the controller
        gpsc = GpsController()
        try:
            gpsc.start()
            while gpsc.fix.latitude is None or gpsc.fix.latitude == 0.0 or math.isnan(gpsc.fix.latitude):
                time.sleep(0.2)
            #gpsc.fix.latitude = 34.6761
            #gpsc.fix.longitude = -82.8346
        except KeyboardInterrupt:
            print "User cancelled"
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise

        finally:
            gpsc.stopController()
            if gpsc.fix.latitude is None or gpsc.fix.latitude == 0.0 or math.isnan(gpsc.fix.latitude):
                print "Could not get a GPS fix, exiting."
                gpsc.join()
                sys.exit()

        print str(gpsc.fix.latitude) + ", " + str(gpsc.fix.longitude)
        activeif = dnet.intf().get_dst(dnet.addr('8.8.8.8'))['name']
        device_id = dnet.intf().get('wlan0')['link_addr']
        if(activeif == 'wlan0'):
            activeif = 'Wifi'
        elif(activeif == 'eth1'):
            activeif = 'eHRPD'
        elif(activeif == 'eth4'):
            activeif = 'WiMAX'
        networks = [{'name':'eHRPD', 'operator':'Sprint'}, {'name':'WiMAX', 'operator': 'Sprint'}]

        #create HTTP POST params/headers #testloc = lat: 34.6761, long: -82.8344
        params = urllib.urlencode({'latitude': gpsc.fix.latitude, 'longitude': gpsc.fix.longitude, 'network_types' : json.dumps(networks), 'active_rat' : activeif, 'device_id' : device_id})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        conn = httplib.HTTPConnection("sciwinet.org", 8888)

        #POST to decision service
        conn.request("POST", "/", params, headers)
        response = conn.getresponse()

        #parse response
        response = json.loads(response.read())
        print "Switching to " + response['network']

        with open('results.csv', 'a') as csvfile:
            writer = csv.writer(csvfile, delimiter=',')
            writer.writerow([str(time.time()), gpsc.fix.latitude, gpsc.fix.longitude, activeif, response['network']])

        #switch interfaces!
        #remove default route

        if response['network'] == activeif:
            time.sleep(10)
            continue

        subprocess.call("route del default", shell=True)
        if response['network'] == 'eHRPD':
            #change default route to 3G
            subprocess.call("route add default gw 192.168.2.5", shell=True)
        elif response['network'] == 'WiMAX':
            #change default route to wimax
            subprocess.call("route add default gw 192.168.1.1", shell=True)
        else:
            #change default route to wifi
            subprocess.call("route add default gw 10.1.1.2", shell=True)

        time.sleep(10)
