from decimal import Decimal
from django import template
from urllib.parse import urlencode

register = template.Library()

@register.simple_tag(takes_context=True)
def param_replace(context, **kwargs):
    """Preserve query parameters when paginating"""
    params = context['request'].GET.copy()
    for key, value in kwargs.items():
        params[key] = value
    return params.urlencode()

@register.filter(name='add_class')
def add_class(field, css):
    return field.as_widget(attrs={"class": css})

# @register.filter
# def sum_attr(items, attr):
#     """Sum a specific attribute from a list of objects"""
#     return sum(getattr(item, attr, 0) for item in items or [])

@register.filter
def sum_debits(transactions):
    return sum(t.debit for t in transactions if t.debit)

@register.filter
def sum_credits(transactions):
    return sum(t.credit for t in transactions if t.credit)

@register.filter
def sum_attr(items, attr):
    return sum(getattr(item, attr, Decimal('0')) for item in items)


@register.filter
def subtract(value, arg):
    """Subtracts the arg from the value"""
    try:
        return float(value) - float(arg)
    except (ValueError, TypeError):
        return 0

# @register.filter
# def sum_debits(transactions):
#     return sum(t.debit for t in transactions)

# @register.filter
# def sum_credits(transactions):
#     return sum(t.credit for t in transactions)