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

from weather.db import get_db
from weather.ingest import (
    fetchHourlyForecasts, fetchDailyForecasts
)

bp = Blueprint('weather', __name__)

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

    if current_conditions is None:
        fetchHourlyForecasts()
        current_conditions = db.execute(
            "SELECT * FROM `current_forecasts` ORDER BY `end_time` DESC LIMIT 1"
        ).fetchone()


    day_or_night = 'day'
    if current_conditions['is_daytime']:
        day_or_night = 'night'

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

    hourly_conditions = db.execute(
        'SELECT * FROM `current_forecasts` WHERE `start_time` > DATETIME("now", "+1 hour") LIMIT 6'
    ).fetchall()
    if len(hourly_conditions) < 6:
        fetchHourlyForecasts()
        hourly_conditions = db.execute(
            'SELECT * FROM `current_forecasts` WHERE `start_time` > DATETIME("now", "+1 hour") LIMIT 6'
        ).fetchall()


    week_forcasts = db.execute(
        'SELECT * FROM `daily_forecasts` WHERE `forecasted_date` > DATETIME("now") LIMIT 7'
    ).fetchall()
    if len(week_forcasts) < 7:
        fetchDailyForecasts()
        week_forcasts = db.execute(
            'SELECT * FROM `current_forecasts` WHERE `start_time` > DATETIME("now", "+1 hour") LIMIT 7'
        ).fetchall()

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

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 'clear'
    elif 'cloud' in condition or 'overcast' in condition:
        return 'cloudy'
    elif 'fog' in condition or 'mist' in condition:
        return 'cloudy'
    else:
        return 'cloudy'


