"""
forecaster.py

This script is designed to run at a regular interval, polling various feeds from the National Weather Service and updating Django models WeatherCondition, WeatherAlert, and WeatherForecast in the Almanac application.

For the current conditions, it grabs the them from the given NWS stations specified in the STATIONS array by their NOAA station ID and saves them as a WeatherConditions object.

When current conditions are checked, the script also looks for weather alerts from NOAA's alert feed for the state specified in STATE. If any are found, a alert object is created and attached to 



"""
from datetime import datetime, timedelta
from dateutil.parser import *
import urllib

# from suds.client import Client
import elementtree.ElementTree as ET

from almanac.models import WeatherConditions, WeatherAlert, WeatherForecast

ALERT_ZONES = {
    "Coastal_Hancock_County": "MEZ029",
}
STATIONS = ["KBGR"]
LOCATIONS = {
    "Castine": "04421",
    "Blue_Hill": "04614",
    "Deer_Isle": "04627",
}

conditions_url = "http://www.weather.gov/xml/current_obs/%s.xml"
alerts_url = "http://www.weather.gov/alerts-beta/wwaatmget.php?x=%s"
forecast_url = "http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
# NOAA=Client(forecast_url)


def coords_for_zipcode(zipcode, client):
    coords = ET.fromstring(client.service.LatLonListZipCode(zipcode))
    coords = coords[0].text.split(",")
    return coords


def update_conditions(conditions):
    """
		function process_conditions
			input: ElementTree object of weather conditions
			result: Look up new weather condition and save it to the db
	"""
    root = conditions.getroot()
    observation_time = parse(root[10].text[:31], ignoretz=True)
    try:
        WeatherConditions.objects.get(observation_time__exact=observation_time)
        print "Passing..."
        pass
    except:
        print "Going ahead..."
        # if root[20].text=="NA":
        wind_gust = 0.0
        # else:
        # 	wind_gust=float(root[20].text)

        # if root[28].text=="NA":
        heat_index = 0.0
        # else:
        # 	heat_index=root[28].text

        if root[25].text == "NA":
            dewpoint = 0
        else:
            dewpoint = float(root[25].text)

        if root[19].text == "NA":
            wind = 0
        else:
            wind = float(root[19].text)

        # if root[31].text=="NA":
        windchill = 0
        # else:
        # 	windchill=int(root[31].text)

        location = root[5].text
        noaa_station_id = root[6].text
        observation_time = parse(root[10].text[:31], ignoretz=True)
        weather = root[11].text
        temperature = float(root[13].text)
        wind_dir = root[17].text
        pressure = float(root[22].text)

        icon_url = root[28].text + root[30].text
        condition = WeatherConditions.objects.create(
            location=location,
            noaa_station_id=noaa_station_id,
            observation_time=observation_time,
            weather=weather,
            temperature_f=temperature,
            wind_dir=wind_dir,
            wind=wind,
            wind_gust=wind_gust,
            pressure=pressure,
            dewpoint=dewpoint,
            heat_index=heat_index,
            windchill=windchill,
            icon_url=icon_url,
        )
        condition.save()


# Create updated conditions for the given stations:
for station in STATIONS:
    conditions = ET.parse(urllib.urlopen(conditions_url % station))
    update_conditions(conditions)


def process_alerts(alerts, zone):
    root = alerts.getroot()
    if (
        root[6][3].text.strip(" ").strip("\n   ")
        == "There are no active watches, warnings or advisories"
    ):
        pass
    else:  # We have a alert, so lets process
        updated = parse(root[6][1].text)
        zone_id = ALERT_ZONES[zone]
        zone = zone.replace("_", " ")
        summary = root[6][5].text.strip("\n")
        effective = parse(root[6][6].text)
        expires = parse(root[6][7].text)
        status = root[6][8].text.strip("\n")
        msg_type = root[6][9].text.strip("\n")
        urgency = root[6][11].text.strip("\n")
        severity = root[6][12].text.strip("\n")
        certainty = root[6][13].text.strip("\n")
        area = root[6][14].text.strip("\n")
        try:
            WeatherAlert.objects.get(summary__exact=summary)
            pass
        except:
            alert = WeatherAlert.objects.create(
                updated=updated,
                zone_id=zone_id,
                zone=zone,
                summary=summary,
                effective=effective,
                expires=expires,
                status=status,
                msg_type=msg_type,
                urgency=urgency,
                severity=severity,
                certainty=certainty,
                area=area,
            )
            alert.save()


# Add alerts for given state
for zone in ALERT_ZONES:
    alerts = ET.parse(urllib.urlopen(alerts_url % ALERT_ZONES[zone]))
    process_alerts(alerts, zone)


# Update current forecasts
"""for loc in LOCATIONS:
	now=datetime.now()
	nowString=datetime.strftime(now,"%Y-%m-%dT%H:%M")
	laterString=datetime.strftime(now + timedelta(days=7),"%Y-%m-%dT%H:%M")
	coords=coords_for_zipcode(LOCATIONS[loc], NOAA)
	forecast=ET.parse(NOAA.service.NDFDgen(coords[0], coords[1], 
		'time-series', nowString, laterString,					
		(1,1,1,1,1,1,1,1,1,1,1,1)))
	print forecast[0]"""


# url = f_url % (lat, lon)
# doc = ET.fromstring(urllib.urlopen(url))
# forecasts=[]
# for node in dom.getElementsByTagNameNS
