"""
Template filters for hospital-related functionality
"""

from django import template

register = template.Library()


@register.filter
def key(dictionary, key_name):
    """
    Get a value from a dictionary by key.

    Usage: {{ mydict|key:"mykey" }}
    """
    if isinstance(dictionary, dict):
        return dictionary.get(key_name)
    return None


@register.filter
def replace(value, arg):
    """
    Replace occurrences of a substring with another substring.

    Usage: {{ value|replace:"old:new" }}
    Example: {{ "hello_world"|replace:"_":" " }} => "hello world"
    """
    if isinstance(value, str) and isinstance(arg, str):
        try:
            old, new = arg.split(":", 1)
            return value.replace(old, new)
        except ValueError:
            return value
    return value


@register.filter
def lookup(dictionary, key):
    """
    Lookup a value from a dictionary by key.

    Usage: {{ my_dict|lookup:key }}
    Example: {{ row|lookup:"column_name" }}
    """
    if isinstance(dictionary, dict):
        return dictionary.get(key)
    return None


@register.filter
def div(value, arg):
    """
    Divide value by arg.

    Usage: {{ value|div:arg }}
    Example: {{ 10|div:2 }} => 5.0
    """
    try:
        return float(value) / float(arg)
    except (ValueError, ZeroDivisionError, TypeError):
        return 0


@register.filter
def mul(value, arg):
    """
    Multiply value by arg.

    Usage: {{ value|mul:arg }}
    Example: {{ 5|mul:3 }} => 15.0
    """
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return 0


@register.simple_tag
def get_all_hospitals():
    """
    Get all hospitals for the hospital switcher dropdown.

    This is used by PX Admins to quickly switch between hospitals
    directly from the header without navigating to the selector page.
    """
    from apps.organizations.models import Hospital

    return Hospital.objects.all().order_by("name", "city")
