from app import app
from datetime import datetime

@app.template_filter('date')
def filter_date(date, format="%Y-%m-%d à %H:%M"):
    """
    Print a date in a human-readable format.
    """

    if date is None:
        return "None"

    if format == "dynamic":
        d = "1er" if date.day == 1 else int(date.day)
        m = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet",
             "Août", "Septembre", "Octobre", "Novembre","Décembre"] \
            [date.month - 1]

        # Omit current year in the last 8 months
        if (datetime.now() - date).days <= 8 * 30:
            format = f"{d} {m} à %H:%M"
        else:
            format = f"{d} {m} %Y à %H:%M"

    return date.strftime(format)

@app.template_filter('dyndate')
def filter_dyndate(date):
    return filter_date(date, format="dynamic")
