from uuid import uuid4

from django import template
from django.template import TemplateDoesNotExist
from django.template.loader import render_to_string
from django.urls import NoReverseMatch, reverse

register = template.Library()


@register.simple_tag
def get_unique_id():
    return uuid4().hex


@register.simple_tag
def optional_url(view_name, *args, **kwargs):
    try:
        return reverse(view_name, args=args, kwargs=kwargs)
    except NoReverseMatch:
        return ""


@register.simple_tag(takes_context=True)
def render_optional_template(context, template_name, **kwargs):
    try:
        rendered_context = (
            context.flatten() if hasattr(context, "flatten") else dict(context)
        )
        rendered_context.update(kwargs)
        return render_to_string(template_name, rendered_context)
    except TemplateDoesNotExist:
        return ""
