from django.http import Http404, HttpResponse, JsonResponse
from django.template.response import TemplateResponse
from django.views import View

from .services import (
    build_manifest_payload,
    get_offline_url,
    get_settings_for_site,
    get_site_for_request,
)


class ManifestView(View):
    def get(self, request):
        site = get_site_for_request(request)
        mobile_app = get_settings_for_site(site)
        if not mobile_app.enable_pwa:
            raise Http404("PWA disabled")
        manifest = build_manifest_payload(
            site, mobile_app, getattr(request, "LANGUAGE_CODE", None)
        )
        return JsonResponse(manifest)


class ServiceWorkerView(View):
    def get(self, request):
        site = get_site_for_request(request)
        mobile_app = get_settings_for_site(site)
        if not mobile_app.enable_pwa:
            return HttpResponse(
                "/* mobile app service worker disabled */",
                content_type="application/javascript",
            )
        context = {
            "site": site,
            "settings_obj": mobile_app,
            "offline_url": get_offline_url(site, mobile_app),
            "manifest_url": request.build_absolute_uri("/manifest.json"),
            "cache_name": f"mobileapp-site-{site.pk}",
        }
        return TemplateResponse(
            request,
            "mobileapp/serviceworker.js",
            context=context,
            content_type="application/javascript",
        )


class OfflineFallbackView(View):
    def get(self, request):
        site = get_site_for_request(request)
        mobile_app = get_settings_for_site(site)
        return TemplateResponse(
            request,
            "mobileapp/offline.html",
            {"site": site, "settings_obj": mobile_app},
        )
