from flask import (
    Blueprint, render_template
)
from werkzeug.exceptions import abort
from datetime import datetime

from weather.db import get_db

bp = Blueprint('weather', __name__)

@bp.route('/')
def index():
    db = get_db()
    current_conditions = dict(db.execute(
        f"SELECT * FROM `reports` WHERE `type` = 'hourly' ORDER BY `end_time` DESC LIMIT 1"
    ).fetchone())

    stale_datetime = datetime.strptime(current_conditions['end_time'], "%Y-%m-%d %H:%M:%S")
    if datetime.now() > stale_datetime:
        # fetch new data
        # save new data

    # TODO: add conditions to check for day/night
    day_or_night = 'day'
    if current_conditions['is_daytime']:
        day_or_night = 'night'

    condition = mapForecastToImage(current_conditions['short_forecast'])
    condition_image = f"images/{time_of_day}_{condition}.jpg"

    hourly_reports = db.execute(
        'SELECT *'
        '  FROM `reports`'
        '  ORDER BY `id` DESC'
        '  LIMIT 7'
    ).fetchall()

    return render_template(
        'weather/index.html',
        current_conditions=current_conditions,
        condition_image=condition_image,
        periods=periods
    )

def mapForecastToImage(condition: str):
    if not condition:
        return 'cloudy'

    condition = condition.lower()
    if 'thunder' in condition or 'storm' in condition:
        return 'stormy'
    elif 'snow' in condition:
        return 'snowy'
    elif 'rain' in condition or 'shower' in condition or 'drizzle' in condition:
        return 'rainy'
    elif 'wind' in condition:
        return 'windy'
    elif 'sunny' in condition or 'clear' in condition:
        return 'sunny'
    elif 'cloud' in condition or 'overcast' in condition:
        return 'cloudy'
    elif 'fog' in condition or 'mist' in condition:
        return 'cloudy'
    else:
        return 'cloudy'

