#!/usr/bin/env python3

import urllib
import datetime
import json
import collections

import rrdtool

from weather_au import api
from dateutil import tz

from pyowm import OWM

owm = OWM('API KEY GOES HERE')
mgr = owm.weather_manager()

# Grab current temps from sensors around the house
#outside = rrdtool.fetch("/media/media/mqtt/ESP_b5952/temp/c.rrd", "AVERAGE")
#rows = outside[2][::-1]
#for data in rows:
#    if data[0] is not None:
#        outside_temp = data[0]
#        break

# Grab outside temp from OpenWeatherMap
observation = mgr.one_call(lat=42.9696, lon=147.2004, exclude='minutely,hourly,daily', units='metric')
outside_temp = int(observation.current.temperature()['temp'])

#bedroom = rrdtool.fetch("/media/media/mqtt/ESP_b3fe20/temp.rrd", "AVERAGE")
#rows = bedroom[2][::-1]
#for data in rows:
#    if data[0] is not None:
#        bedroom_temp = int(data[0])
#        break
bedroom_temp = 0

lounge = rrdtool.fetch("/media/media/mqtt/ESP_4c7682/temp.rrd", "AVERAGE")
rows = lounge[2][::-1]
try:
    lounge_temp = int(rows[1][0])
except TypeError:
    try:
        lounge_temp = int(rows[2][0])
    except TypeError:
        lounge_temp = "N"

bom_icons = {
    'sunny': 'SUNNY.JPG',
    'clear': 'CLEAR.JPG',
    'partly_cloudy': 'PCLOUD.JPG',
    'mostly_sunny': 'PCLOUD.JPG',
    'cloudy': 'CLOUDY.JPG',
    'haze': 'HAZE.JPG',
    'light_rain': 'LRAIN.JPG',
    'wind': 'WIND.JPG',
    'windy': 'WIND.JPG',
    'fog': 'FOG.JPG',
    'shower': 'SHOWER.JPG',
    'rain': 'RAIN.JPG',
    'dust': 'DUST.JPG',
    'frost': 'FROST.JPG',
    'snow': 'SNOW.JPG',
    'storm': 'STORM.JPG',
    'light_showers': 'LSHOWE.JPG',
    'light_shower': 'LSHOWE.JPG',
    'heavy_showers': 'HSHOWE.JPG',
    'cyclone': 'CYCLON.JPG'
}


w = api.WeatherApi(search="longley+tas")

wdays_dict = w.forecasts_daily()

new = {}
weather = {}

# The first forecast period doesn't always have the temperature and other bits
# I get the overnight low and forecast to substitute when this happens.

if wdays_dict[0]['temp_min'] is None:
    night = 1
    weather['today'] = wdays_dict[0]
    weather['tomorrow'] = wdays_dict[1]
    weather['day_after'] = wdays_dict[2]
else:
    night = 0
    weather['today'] = wdays_dict[0]
    weather['tomorrow'] = wdays_dict[1]
    weather['day_after'] = wdays_dict[2]

utc_zone = tz.tzutc()
local_zone = tz.tzlocal()

if night:
    for day in weather.keys():
        new[day] = {}
        if (day == 'today'):
            new[day]['day'] = 'Tonight'
            new[day]['max'] = weather['tomorrow']['temp_min']
            new[day]['icon'] = bom_icons[weather['today']['icon_descriptor']]
        else:
            utc = datetime.datetime.strptime(weather[day]['date'], "%Y-%m-%dT%H:%M:%S%z")
            utc.replace(tzinfo=utc_zone)
            local_date = utc.astimezone(local_zone)
            new[day]['day'] = local_date.strftime("%A")
            new[day]['icon'] = bom_icons[weather[day]['icon_descriptor']]
            new[day]['max'] = weather[day]['temp_max']

else:

    for day in weather.keys():
        new[day] = {}
        utc = datetime.datetime.strptime(weather[day]['date'], "%Y-%m-%dT%H:%M:%S%z")
        utc.replace(tzinfo=utc_zone)
        local_date = utc.astimezone(local_zone)
        new[day]['day'] = local_date.strftime("%A")
        new[day]['icon'] = bom_icons[weather[day]['icon_descriptor']]
        new[day]['max'] = weather[day]['temp_max']


new['current'] = {}
new['current']['outside'] = outside_temp
new['current']['bedroom'] = bedroom_temp
new['current']['lounge'] = lounge_temp

with open('/var/www/darksky/bom.json', 'w') as output:
    output.write(json.dumps(new))
    output.close()

