import json
from urllib.parse import unquote

from django.http import HttpRequest
from django.utils.functional import cached_property


class HtmxMiddleware:
    """Simply copied form Django"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        request.htmx = HtmxDetails(request)
        return self.get_response(request)


class HtmxDetails:
    def __init__(self, request):
        self.request = request

    def _get_header_value(self, name):
        value = self.request.headers.get(name) or None
        if value:
            if self.request.headers.get(f"{name}-URI-AutoEncoded") == "true":
                value = unquote(value)
        return value

    def __bool__(self):
        return self._get_header_value("HX-Request") == "true"

    @cached_property
    def boosted(self):
        return self._get_header_value("HX-Boosted") == "true"

    @cached_property
    def current_url(self):
        return self._get_header_value("HX-Current-URL")

    @cached_property
    def history_restore_request(self):
        return self._get_header_value("HX-History-Restore-Request") == "true"

    @cached_property
    def prompt(self):
        return self._get_header_value("HX-Prompt")

    @cached_property
    def target(self):
        return self._get_header_value("HX-Target")

    @cached_property
    def trigger(self):
        return self._get_header_value("HX-Trigger")

    @cached_property
    def trigger_name(self):
        return self._get_header_value("HX-Trigger-Name")

    @cached_property
    def triggering_event(self):
        value = self._get_header_value("Triggering-Event")
        if value is not None:
            try:
                value = json.loads(value)
            except json.JSONDecodeError:
                value = None
        return value
