from django import template
from django.template import Context
from django.template.defaultfilters import floatformat


register = template.Library()

@register.filter
def attr(obj, attr_name):
    """
    Retrieves an attribute of an object dynamically in the template.
    """
    return getattr(obj, attr_name, None)

@register.filter
def class_name(value):
    """
    Returns the class name of the given object.
    """
    return value.__class__.__name__

@register.simple_tag(takes_context=True)
def render_breadcrumbs(context, breadcrumbs):
    """
    Render breadcrumbs using a separate template file.
    """
    return context.template.engine.get_template('partials/breadcrumbs.html').render(
    Context({
        'breadcrumbs': breadcrumbs
    }))

@register.filter
def safe_floatformat(value, decimal_places):
    try:
        # Attempt to convert the value to a float
        value = float(value)
        
        # Check if the value is an integer
        if value.is_integer():
            return int(value)  # Return as an integer
        
        # Otherwise, format as a float with the specified decimal places
        return floatformat(value, decimal_places)
    except (ValueError, TypeError):
        # If the value is not a number, return it as is
        return value

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key, None)

@register.filter
def is_bool(value):
    return isinstance(value, bool)
