import threading
from django.http import HttpResponse

class LoadingPageMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Create a loading response
        loading_response = self.create_loading_response()

        # Start a new thread to handle the actual response
        thread = threading.Thread(target=self.handle_actual_response, args=(request, loading_response))
        thread.start()

        # Return the loading response
        return loading_response

    def handle_actual_response(self, request, loading_response):
        # Get the actual response asynchronously
        actual_response = self.get_response(request)

        # Replace the content of the loading response with the actual response content
        loading_response.content = actual_response.content
        loading_response.status_code = actual_response.status_code

    def create_loading_response(self):
        # Create a simple loading response
        loading_content = b'<div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); z-index: 9999;">Loading...</div>'
        return HttpResponse(loading_content)

