import logging

from django.conf import settings
from django.contrib import auth
from django.utils.module_loading import import_string
from django.http import JsonResponse

from mozilla_django_oidc.views import OIDCLogoutView, get_next_url

logger = logging.getLogger(__name__)


class NoRedirectOIDCLogoutView(OIDCLogoutView):

    def post(self, request):

        logout_url = self.redirect_url
        client_id = settings.OIDC_RP_CLIENT_ID
        next_url = get_next_url(request, "next")

        # Not propagating redirect url right now due to issue with keycloak
        # accepting it
        if next_url and False:
            if not logout_url.endswith("/"):
                logout_url += "/"
            logout_url += f"?client_id={client_id}&post_logout_redirect_uri={next_url}"

        if request.user.is_authenticated:
            # Check if a method exists to build the URL to log out the user
            # from the OP.
            logout_from_op = self.get_settings("OIDC_OP_LOGOUT_URL_METHOD", "")
            if logout_from_op:
                logout_url = import_string(logout_from_op)(request)

            # Log out the Django user if they were logged in.
            auth.logout(request)
        return JsonResponse({"url": logout_url})
