"""
Template tags for tree component.

Provides reusable components for displaying hierarchical tree structures.
"""
from django import template

register = template.Library()


@register.filter
def get_item(dictionary, key):
    """
    Get an item from a dictionary using a key, or an attribute from an object.
    
    Usage:
        {{ node|get_item:"id" }}
        {{ node|get_item:"taxon_id" }}
    """
    if hasattr(dictionary, key):
        return getattr(dictionary, key)
    elif isinstance(dictionary, dict):
        return dictionary.get(key)
    return None


@register.inclusion_tag('components/tree.html', takes_context=False)
def tree(nodes, node_id_field, children_url_name, node_label_field='label', 
         node_children_count_field='children_count', query_string='', 
         render_node_content=None, tree_id='tree', tree_class=''):
    """
    Display a hierarchical tree component with lazy loading.
    
    Args:
        nodes: List of node objects to render
        node_id_field: Field name on node object that contains the unique ID (e.g., 'id', 'taxon_id')
        children_url_name: URL name for fetching children (will be called with node_id as argument)
        node_label_field: Field name for node label (default: 'label')
        node_children_count_field: Field name for children count (default: 'children_count')
        query_string: Query string to append to children URL (e.g., '?order=rank')
        render_node_content: Template path for custom node content rendering (optional)
        tree_id: Unique identifier for this tree instance (default: 'tree')
        tree_class: Additional CSS classes for the tree root container (default: '')
    
    Usage:
        {% load tree_tags %}
        {% tree nodes=my_nodes node_id_field="taxon_id" children_url_name="myapp:browse-node" query_string="?order=rank" %}
    """
    return {
        'nodes': nodes,
        'node_id_field': node_id_field,
        'children_url_name': children_url_name,
        'node_label_field': node_label_field,
        'node_children_count_field': node_children_count_field,
        'query_string': query_string,
        'render_node_content': render_node_content,
        'tree_id': tree_id,
        'tree_class': tree_class,
    }
