#!/usr/bin/env python3

import requests
import json
import psycopg2
import psycopg2.extensions
from datetime import datetime, timezone
import re


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


def polygon_pop():
    cursor.execute("select warnindex from svr where polygonpop is null")
    polys_to_update = cursor.fetchall()
    sql = "update svr set polygonpop = (select(St_SummaryStats(st_clip(rlxpop.rast, svr.nwspoly, true))).sum::int from rlxpop,svr where warnindex = %s) where warnindex = %s"
    for p in polys_to_update:
       vals = p,p
       cursor.execute(sql,vals)
    conn.commit()



def verify_severe():
  cursor.execute('select vtec from svr where EXTRACT(EPOCH FROM (current_timestamp - endtime ))/60/60/24  < 3')
  svr = cursor.fetchall()
  #print(svr)
  for i in svr:
   sql = "select sum (power.outagen) as total from power,svr where svr.vtec = %s and ST_Contains(svr.nwspoly,power.realgeom) and power.startguess > svr.issue and power.startguess < svr.endtime + (120 ||'minutes')::interval group by svr.vtec"
   val = (i,)
   cursor.execute(sql,val)
   svrout = cursor.fetchall()
   try:
    if svrout[0][0] == None:
     svroutages = 0
    else:
     svroutages = str(svrout[0][0])
     sql = 'update svr set outagesvalid = %s where vtec = %s'
     val = (svroutages,i)
     cursor.execute(sql,val)
#     info = {'vtec': str(i[0]), 'outagesvalid': svroutages}
#     svrinfo.append(info)

   except:
    svroutages = 0
    sql = 'update svr set outagesvalid = %s where vtec = %s'
    val = (svroutages,i)
    cursor.execute(sql,val)
    conn.commit()
#    info = {'vtec': str(i[0]), 'outagesvalid': svroutages}
#    svrinfo.append(info)
   conn.commit()

#select  sum (power.outagen) as total from power,svr where st_contains(st_buffer(svr.nwspoly, .1,'side=left join=mitre quad_segs=32'),power.realgeom) and power.startguess > svr.issue and power.startguess < svr.endtime + (60 ||'minutes')::interval group by svr.vtec
#select nwspoly, st_buffer(svr.nwspoly, .072,'side=left join=mitre quad_segs=32') from svr limit 1
def verify_severe_buffer():
  cursor.execute('select vtec from svr where EXTRACT(EPOCH FROM (current_timestamp - endtime ))/60/60/24  < 3')
  svr = cursor.fetchall()
  #print(svr)
  for i in svr:
   sql = "select sum (power.outagen) as total from power,svr where svr.vtec = %s and ST_Contains(st_buffer(svr.nwspoly, .072,'side=left join=mitre quad_segs=32'),power.realgeom) and power.startguess > svr.issue and power.startguess < svr.endtime + (120 ||'minutes')::interval group by svr.vtec"
   val = (i,)
   cursor.execute(sql,val)
   svrout = cursor.fetchall()
   try:
    if svrout[0][0] == None:
     svroutages = 0
    else:
     svroutages = str(svrout[0][0])
     sql = 'update svr set outagesbuffer = %s where vtec = %s'
     val = (svroutages,i)
     cursor.execute(sql,val)
#     info = {'vtec': str(i[0]), 'outagesvalid': svroutages}
#     svrinfo.append(info)

   except:
    svroutages = 0
    sql = 'update svr set outagesbuffer = %s where vtec = %s'
    val = (svroutages,i)
    cursor.execute(sql,val)
    conn.commit()
#    info = {'vtec': str(i[0]), 'outagesbuffer': svroutages}
#    svrinfo.append(info)
   conn.commit()







svrinfo = []
verify_severe()
verify_severe_buffer()



cursor.execute('select vtec,outagesvalid,polygonpop,outagesbuffer from svr where EXTRACT(EPOCH FROM (current_timestamp - endtime ))/60/60/24  < 60')
svrout = cursor.fetchall()

polygon_pop()

for i in svrout:
    info = {'vtec': str(i[0]), 'outagesvalid': i[1], 'polygonpop': int(i[2]), 'percout': round(i[1]*2.5/int(i[2])*1000)/10, 'outagesbuffer': i[3]}
    svrinfo.append(info)



with open("/var/www/html/work/svr.json", "w") as outfile:
 outfile.write(json.dumps(svrinfo))

cursor.close()
conn.close()
