# templatetags/bilal_extras.py
from django import template

register = template.Library()


@register.filter
def lookup(dictionary, key):
    """
    Filtre personnalisé pour rechercher une valeur dans un dictionnaire ou une liste de tuples
    Usage: {{ dict|lookup:key }}
    """
    if isinstance(dictionary, dict):
        return dictionary.get(key, '')

    # Pour les choix Django (liste de tuples)
    if isinstance(dictionary, (list, tuple)):
        for choice_key, choice_value in dictionary:
            if choice_key == key:
                return choice_value

    return ''


@register.filter
def get_item(dictionary, key):
    """
    Alias pour lookup - récupère un élément par clé
    """
    return lookup(dictionary, key)


@register.simple_tag
def get_choice_display(choices, value):
    """
    Tag simple pour afficher le nom d'un choix
    Usage: {% get_choice_display choices value %}
    """
    for choice_key, choice_value in choices:
        if choice_key == value:
            return choice_value
    return value


@register.inclusion_tag('bilal/tags/category_display.html')
def category_display(categories, selected_category):
    """
    Tag d'inclusion pour afficher une catégorie
    """
    category_name = ''
    if selected_category:
        for code, name in categories:
            if code == selected_category:
                category_name = name
                break

    return {
        'category_name': category_name,
        'selected_category': selected_category
    }