from django import template

register = template.Library()


@register.filter
def branch_label(branch_id, mapping):
    """Branch name for a stored branch id.  {{ obj.branch_id|branch_label:branch_map }}

    Tenant rows only store the branch id (no SQL join to the shared DB), and rows
    created before branches existed have no id - they belong to the main branch.
    """
    if not mapping:
        return "-"
    if not branch_id:
        return mapping.get("__main__", "-")
    return mapping.get(str(branch_id), "-")


@register.filter
def get_item(mapping, key):
    """{{ some_dict|get_item:key }}"""
    try:
        return mapping.get(key)
    except AttributeError:
        return None
