from urllib import parse

from dateutil.relativedelta import relativedelta
from django import template
from django.templatetags.static import static
from django.urls import reverse
from django.utils import formats
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter
def value(val, pm=False, r=2):
    if val is None:
        return ""
    _prefix = ""
    _suffix = "&nbsp;€"
    _val = formats.number_format(val, decimal_pos=r, use_l10n=True, force_grouping=True)

    if val > 0:
        if pm:
            _prefix += "&plus;&nbsp;"
    elif val < 0:
        _val = _val[1:]
        _prefix += "&minus;&nbsp;"

    return mark_safe(f"{_prefix}{_val}{_suffix}")


@register.filter
def pmvalue(val):
    return value(val, True)


@register.filter
def pmrvalue(val):
    return value(val, True, r=0)


@register.filter
def remix(icon, *args):
    return remixnl(f"{icon}-line", *args)


@register.filter
def remixnl(icon, cls=""):
    return mark_safe(f"""<span class="ri-{icon} {cls}"></span>""")


@register.filter
def messageicon(level):
    ico = {
        10: "bug",
        20: "information",
        25: "check",
        30: "alert",
        40: "error-warning",
    }

    return remix(ico.get(level, "question"))


@register.filter
def extension(file):
    return file.name.split(".", 1)[1].upper()


@register.filter
def verbose_name(obj):
    return obj._meta.verbose_name


@register.filter
def adding(obj):
    return obj._state.adding


@register.simple_tag
def css(href):
    return mark_safe(
        f"""<link rel="stylesheet" href="{static(href)}" type="text/css">"""
    )


@register.simple_tag
def js(href):
    return mark_safe(f"""<script src="{static(href)}" defer></script>""")


@register.filter
def balance(accounts):
    return sum(
        statement.value for acc in accounts if (statement := acc.statement_set.first())
    )


@register.inclusion_tag("main/pagination_links.html", takes_context=True)
def pagination_links(context, page_obj):
    _n = 3
    return {
        "request": context["request"],
        "pages": [
            {"number": p, "current": p == page_obj.number}
            for p in page_obj.paginator.page_range
            if abs(p - page_obj.number) < _n
        ],
        "first": {
            "show": page_obj.number > _n,
            "dots": page_obj.number > _n + 1,
        },
        "last": {
            "show": page_obj.number <= page_obj.paginator.num_pages - _n,
            "dots": page_obj.number < page_obj.paginator.num_pages - _n,
            "number": page_obj.paginator.num_pages,
        },
    }


@register.simple_tag(takes_context=True)
def page_url(context, page):
    query = context["request"].GET.copy()
    query["page"] = page
    return query.urlencode()


@register.simple_tag
def url_get(name, **kwargs):
    kwargs = {k: v for k, v in kwargs.items() if v}
    return f"{reverse(name)}?{parse.urlencode(kwargs)}"


@register.filter
def end_of_month(month):
    return month + relativedelta(months=1, days=-1)


@register.filter
def end_of_year(year):
    return year + relativedelta(years=1, days=-1)
