#!/usr/bin/env python3

import datetime
import json

from weather_au import api
from dateutil import tz

from homeassistant_api import Client

client = Client('https://ha.thewarrens.name/api/',
                'API_KEY_GOES_HERE')

# Grab outside temp from OpenWeatherMap via HomeAssistant
outside_temp = round(float(client.get_state(
    entity_id='sensor.openweathermap_temperature').state))

# bedroom only needed for the clock to read in the json
bedroom_temp = 0

# get lounge temp from HomeAssistant
lounge_temp = round(float(client.get_state(
    entity_id='sensor.lounge_temperature').state))

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()
