import time
import requests
import json
import psycopg2
import psycopg2.extensions
from psycopg2.extras import Json


conn = psycopg2.connect(host='127.0.0.1', database='nws', user='nws', password='nws')
cursor = conn.cursor()




updates = ['UPDATE public.cams SET geom = ST_SetSRID(ST_MakePoint(lon, lat), 4326)',
'UPDATE public.cams SET county = county.countyname from public.county WHERE ST_Contains(county.geom,cams.geom)',
'UPDATE public.cams SET pzone = pzone.state_zone from public.pzone WHERE ST_Contains(pzone.geom,cams.geom)',
'UPDATE public.cams SET fzone = fzone.state_zone from public.fzone WHERE ST_Contains(fzone.geom,cams.geom)',
'UPDATE public.cams SET cwa = fzone.cwa from public.fzone WHERE ST_Contains(fzone.geom,cams.geom)',
'UPDATE public.cams SET zonename = pzone.shortname from public.pzone WHERE ST_Contains(pzone.geom,cams.geom)',
'UPDATE public.cams SET state = county.state from public.county WHERE ST_Contains(county.geom,cams.geom)']

for i in updates:
 cursor.execute(i)



conn.commit()



headers = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    }

cursor.execute("SELECT camid, lon, lat from cams WHERE elevation ISNULL")
allcams = cursor.fetchall()



def get_elev(lon,lat):
 sql = "SELECT round(ST_Value(rast, ST_SetSRID(ST_MakePoint(%s,%s),4326)) * 3.28084) AS val FROM dem WHERE ST_Intersects(rast, ST_SetSRID(ST_MakePoint(%s,%s),4326))"
 vars = (lon,lat,lon,lat)
 cursor.execute(sql,vars)
 elev = cursor.fetchone()
 print(elev)
 if (elev != None):
  return int(elev[0])
 if (elev == None):
  elev = get_elev_backup(lon,lat)
  print('backup: ' +str(elev))
  return int(elev)

def get_elev_backup(lon,lat):
  baseurl = 'https://nationalmap.gov/epqs/pqs.php?x={}&y={}&units=Feet&output=json'.format(lon,lat)
  r = requests.get(baseurl, timeout=3,headers=headers)
  if r.status_code == 200:
   returns = r.json()
   elev = returns.get('USGS_Elevation_Point_Query_Service').get('Elevation_Query').get('Elevation')
   return elev



for cam in allcams:
 camid, lon, lat = cam
 elev = get_elev(lon,lat)
 val = (elev,camid)
 sql = "UPDATE cams SET elevation= %s WHERE camid = %s"
 cursor.execute(sql,val)
 conn.commit()

