import datetime as dt
import locale
import os

from bottle import hook, redirect, request, route, run, static_file, view
from dateutil.relativedelta import *

import models
from fioul import get_today_prices_from_internet
from models import Price

# ----------------------------------------------------------------------
# Web application


@route("/")
def home():
    today = dt.date.today()
    return redirect(f"/{today.year}/{today.month}")


@route("/<year:int>/<month:int>")
@view("search_results", template_settings={"noescape": True})
def results_page(year, month):
    results = Price.select().order_by(Price.date.desc())
    start = dt.date(year, month, day=1)
    prev = start + relativedelta(months=-1)
    next = start + relativedelta(months=+1)
    print(f"debug upper date boundary: {start + relativedelta(months=1)}")
    month_results = (
        Price.select()
        .where(
            Price.date >= start,
            Price.date < next,
        )
        .order_by(Price.date.desc())
    )
    prev_page = f"/{prev.year}/{prev.month}"
    next_page = f"/{next.year}/{next.month}"
    displayed_month = start.strftime("%B %Y")
    print(f"year: {year}, month: {month}, displayed: {displayed_month}")
    current_500, current_1000 = get_today_prices_from_internet()
    day_classes = {
        0: "monday",
        1: "tuesday",
        2: "wednesday",
        3: "thursday",
        4: "friday",
        5: "saturday",
        6: "sunday",
    }
    return dict(
        results=results,
        month_results=month_results,
        prev_page=prev_page,
        next_page=next_page,
        displayed_month=displayed_month,
        day_classes=day_classes,
        current_500=current_500,
        current_1000=current_1000,
    )


@route("/static/<filename>")
def serve_static_file(filename):
    project_dir = os.path.dirname(__file__)
    static_root = os.path.join(project_dir, "static")
    return static_file(filename, root=static_root)


@hook("before_request")
def set_locale():
    """Set the locale for all categories to the first lang in Accept-Language
    header. Default to fr_FR.UTF-8
    """
    accept_language = request.get_header("Accept-Language", "fr-FR")
    first_lang = accept_language.split(";")[0].split(",")[0]
    lang = first_lang.translate(str.maketrans("-", "_")) + ".UTF-8"
    try:
        locale.setlocale(locale.LC_ALL, lang)
    except locale.Error:
        locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")


@hook("before_request")
def connect_to_db():
    models.db.connect()


@hook("after_request")
def close_db_connection():
    models.db.close()
