from django import template
from django.template.loader import render_to_string
from django.urls import reverse

from ..services import (
    build_bridge_context,
    build_head_context,
    get_settings_for_site,
    get_site_for_request,
)

register = template.Library()


@register.simple_tag(takes_context=True)
def mobile_app_head(context):
    request = context.get("request")
    if request is None:
        return ""
    head_context = build_head_context(request)
    if not head_context["enabled"]:
        return ""
    return render_to_string("mobileapp/head.html", head_context, request=request)


@register.simple_tag(takes_context=True)
def mobile_app_service_worker(context):
    request = context.get("request")
    if request is None:
        return ""
    site = get_site_for_request(request)
    mobile_app = get_settings_for_site(site)
    if not mobile_app.enable_pwa or request.path.startswith("/admin/"):
        return ""
    return render_to_string(
        "mobileapp/service_worker_registration.html",
        {
            "service_worker_url": reverse("mobileapp_serviceworker"),
            "scope": mobile_app.scope or "/",
        },
        request=request,
    )


@register.simple_tag(takes_context=True)
def mobile_app_bridge(context):
    request = context.get("request")
    if request is None:
        return ""
    bridge_context = build_bridge_context(request)
    if not bridge_context["enabled"] or request.path.startswith("/admin/"):
        return ""
    return render_to_string(
        "mobileapp/bridge.html",
        bridge_context,
        request=request,
    )
