import datetime
import math
from urllib import parse

from django import template
from django.urls import reverse
from django.utils.safestring import mark_safe
from history.utils import history
from main.templatetags.main_extras import pmrvalue, remix

register = template.Library()


@register.inclusion_tag("history/plot.html", takes_context=True)
def history_plot(context, transactions, **kwargs):
    kwargs.setdefault("account", context.get("account"))
    kwargs.setdefault("category", context.get("category"))

    if kwargs.get("category") or kwargs.get("account"):
        kwargs["history"] = history(transactions.all())
    else:
        kwargs["history"] = history(transactions.exclude(category__budget=False))

    return kwargs


@register.simple_tag
def calendar_opacity(v, vmax):
    if v is None:
        return "0%"
    return f"{math.sin(min(1, math.fabs(v/vmax))*math.pi/2): .0%}"


@register.simple_tag
def empty_calendar_cells(n):
    return mark_safe(n * "<td></td>")


@register.simple_tag
def empty_calendar_cells_start(n):
    return empty_calendar_cells(n - 1)


@register.simple_tag
def empty_calendar_cells_end(n):
    return empty_calendar_cells(12 - n)


@register.simple_tag
def up_down_icon(val):
    if val is None:
        return ""
    if val > 0:
        return remix("arrow-up-s", "green")
    elif val < 0:
        return remix("arrow-down-s", "red")

    return remix("equal", "white")


@register.simple_tag
def plot_bar(s, sum_pm, s_max):
    _res = ""

    if s_max:
        if sum_pm:
            _w = abs(sum_pm / s_max)
            _res += f"""<div style="width: {_w: .1%}"></div>"""
        if sum_pm is not None and s * sum_pm > 0:
            _w = abs(s / s_max)
            _res += (
                f"""<div class="tot" style="width: {_w: .1%}">"""
                f"""<span>{pmrvalue(s)}</span></div>"""
            )
    else:
        _res += "<div></div>"

    return mark_safe(_res)


@register.simple_tag
def calendar_head():
    months = range(1, 13)
    th = (f"""<th>{month: 02d}</th>""" for month in months)

    return mark_safe("".join(th))


@register.filter
def sum_year(y_data):
    return sum(y["sum"] or 0 for y in y_data)


@register.inclusion_tag("history/pagination.html", takes_context=True)
def history_pagination(context):
    return context


@register.simple_tag(takes_context=True)
def history_url(context, month=None, year=None, clear=False, **kwargs):
    if not clear:
        kwargs.setdefault("account", getattr(context.get("account"), "id", None))
        kwargs.setdefault("category", getattr(context.get("category"), "id", None))

    if month:
        if isinstance(month, datetime.date):
            year = month.year
            month = month.month
        url = reverse("history:month", kwargs={"year": year, "month": month})
    elif year:
        if isinstance(year, datetime.date):
            year = year.year
        url = reverse("history:year", kwargs={"year": year})

    kwargs = {k: v for k, v in kwargs.items() if v}

    if kwargs:
        return f"{url}?{parse.urlencode(kwargs)}"
    return url
