from django import template
from django.db import models
from django.db.models.functions import Greatest

register = template.Library()


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

    if not kwargs.get("account"):
        transactions = transactions.exclude(category__budget=False)
    categories = (
        transactions.values("category", "category__name", "category__icon")
        .annotate(
            sum=models.Sum("value"),
            sum_m=models.Sum("value", filter=models.Q(value__lt=0)),
            sum_p=models.Sum("value", filter=models.Q(value__gt=0)),
        )
        .order_by("-sum")
    )
    return (
        kwargs
        | {
            "categories": categories,
        }
        | categories.aggregate(
            max=Greatest(-models.Sum("sum_m"), models.Sum("sum_p")),
            total_m=models.Sum("sum_m"),
            total_p=models.Sum("sum_p"),
            total=models.Sum("sum"),
        )
    )
