from datetime import datetime, timedelta

from almanac.models import WeatherConditions, Day
from directory.models import Town

""" Condition archiver. 

    This script is designed to be run once a day, preferably as early as possible.

    It does the following things:

      * Grabs all conditions for previous day.
      * Generates avg, high, and low temps for past day
      * Generates avg. pressure and humidity
      * Grabs the first Conditions weather condition
      * Stores all results in the corresponding "Day" object

    The purpose of this script is to develop and "archive" of weather, so we 
    can provide our own weather history for each day."""

yesterday = Day.objects.get(date__exact=(datetime.now() + timedelta(days=-1)).date())

daily = {"avg": 0, "high": -60, "low": 120}
monthly_avg = 0
yearly_avg = 0
daily_conditions = (
    WeatherConditions.objects.filter(
        town__slug="stonington", observation_time__year=yesterday.date.year
    )
    .filter(observation_time__month=yesterday.date.month)
    .filter(observation_time__day=yesterday.date.day)
)
monthly_conditions = WeatherConditions.objects.filter(
    town__slug="stonington", observation_time__year=yesterday.date.year
).filter(observation_time__month=yesterday.date.month)
yearly_conditions = WeatherConditions.objects.filter(
    town__slug="stonington", observation_time__year=yesterday.date.year
)

if daily_conditions:
    for c in daily_conditions:
        daily["avg"] += c.temperature
    if c.temperature > daily["high"]:
        daily["high"] = c.temperature
    if c.temperature < daily["low"]:
        daily["low"] = c.temperature

    for c in monthly_conditions:
        monthly_avg += c.temperature

    for c in yearly_conditions:
        yearly_avg += c.temperature

    if monthly_avg != 0:
        monthly_avg = monthly_avg / len(monthly_conditions)
    if yearly_avg != 0:
        yearly_avg = yearly_avg / len(yearly_conditions)

    if daily_conditions:
        daily["avg"] = daily["avg"] / len(daily_conditions)
    yesterday.daily_avg_temp = str(daily["avg"])
    yesterday.daily_high_temp = str(daily["high"])
    yesterday.daily_low_temp = str(daily["low"])
    yesterday.monthly_avg_temp = str(monthly_avg)
    yesterday.yearly_avg_temp = str(yearly_avg)
    yesterday.save()
