from tabulate import tabulate
import requests
import polyline
import json
import psycopg2
import psycopg2.extensions
from datetime import datetime, timezone
from geojson import Point, Feature, FeatureCollection, dump

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

cursor.execute("""
    SELECT 
        startguess::timestamp(0),
        lastchange::timestamp(0),
        (lastchange-startguess)::interval(0),
        peakoutage,
        cause,
        lat,
        lon,
        county,
        state 
    FROM 
        power 
    WHERE 
        (cause ILIKE '%%tree%%' OR cause ILIKE '%%weather%%') 
        AND cwa = 'RLX' 
        AND startguess BETWEEN now() - interval '120 hours' AND now() 
    ORDER BY 
        startguess DESC
""")
allweather = cursor.fetchall()
cleanprint = []
#print(allweather)


if len(allweather) == 0:
 outage = ("No Tree Damage or Weather Reports In The Last 24 Hours")
else:
 outage = tabulate(allweather,headers=['Start Time UTC', 'End Time UTC','Duration','Max Out','Cause','Lat','Lon','County','State'])


with open("/var/www/html/work/24hrpower.txt", "w") as outfile:
       outfile.write(outage)




cursor.close()
conn.close()
