"""
Block the app until installation is complete.
"""
from django.shortcuts import redirect
from django.urls import reverse


class InstallerMiddleware:
    """
    If storage/installed is missing, force visitors into /install/.
    After install, /install/ redirects to home/login.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        from apps.installer.utils import is_installed

        path = request.path
        exempt = (
            path.startswith('/install/')
            or path.startswith('/static/')
            or path.startswith('/media/')
        )

        installed = is_installed()

        if not installed and not exempt:
            return redirect('installer:welcome')

        if installed and path.startswith('/install/') and not path.startswith('/install/complete'):
            # Allow complete page briefly; otherwise block re-install
            if path.rstrip('/') != '/install/complete':
                return redirect('home')

        return self.get_response(request)
