import datetime

from django import template
from django.template.defaultfilters import date
from django.urls import reverse
from django.utils.safestring import mark_safe

from ..utils import ac_url

register = template.Library()


@register.inclusion_tag("transaction/transaction_table.html", takes_context=True)
def transaction_table(context, transactions, n_max=None, **kwargs):
    if n_max is not None:
        if transactions.count() <= n_max:
            del kwargs["transactions_url"]
        transactions = transactions[:n_max]

    kwargs.setdefault("hide_account", "account" in context or "statement" in context)
    kwargs.setdefault("hide_category", "category" in context)

    ncol = 8
    if kwargs.get("hide_account"):
        ncol -= 1
    if kwargs.get("hide_category"):
        ncol -= 1

    return kwargs | {"transactions": transactions, "ncol": ncol}


@register.inclusion_tag("transaction/transaction_filters.html", takes_context=True)
def transaction_filters(context, **kwargs):
    kwargs.setdefault("filters", context.get("filters"))
    return kwargs


@register.inclusion_tag("transaction/invoice_table.html")
def invoice_table(transaction=None, **kwargs):
    if transaction:
        kwargs.setdefault("invoices", transaction.invoice_set.all())

    return kwargs | {
        "transaction": transaction,
    }


@register.simple_tag(takes_context=True)
def month_url(context, month, cls="", fmt="Y-m"):
    url_name, url_params = ac_url(
        "transaction_month", {"year": month.year, "month": month.month}, context
    )

    url = reverse(url_name, kwargs=url_params)
    return mark_safe(
        f"""<a class="{cls}" href="{url}"><time datetime="{date(month, "Y-m")}">"""
        f"""{date(month, fmt).capitalize()}</time></a>"""
    )


@register.simple_tag(takes_context=True)
def year_url(context, year, cls=""):
    if isinstance(year, datetime.date):
        year = year.year
    url_name, url_params = ac_url("transaction_year", {"year": year}, context)

    url = reverse(url_name, kwargs=url_params)
    return mark_safe(
        f"""<a class="{cls}" href="{url}">"""
        f"""<time datetime="{year}">{year}</time></a>"""
    )
