from django.shortcuts import get_object_or_404
from django.urls import resolve
from django_scopes import scope, scopes_disabled

from servala.core.models import Organization


class OrganizationMiddleware:

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

    def __call__(self, request):
        url = resolve(request.path_info)

        if "admin" in url.namespaces:
            with scopes_disabled():
                return self.get_response(request)

        organization_slug = url.kwargs.get("organization")
        if organization_slug:
            pk = organization_slug.rsplit("-", maxsplit=1)[-1]
            try:
                pk = int(pk)
            except ValueError:
                pk = -1
            request.organization = get_object_or_404(Organization, pk=pk)
            with scope(organization=request.organization):
                return self.get_response(request)

        request.organization = None
        return self.get_response(request)
