from urllib.parse import urlencode

from django.urls import reverse
from wagtail.admin.views.pages.choose_parent import ChooseParentView


class ListingRedirectChooseParentView(ChooseParentView):
    """ChooseParentView that redirects new pages back to a listing viewset.

    Subclasses set ``listing_url_name`` (e.g. ``"events:index"``).
    """

    listing_url_name: str

    def _with_next(self, response):
        if response.status_code != 302:
            return response
        url = response["Location"]
        sep = "&" if "?" in url else "?"
        response["Location"] = f"{url}{sep}{urlencode({'next': reverse(self.listing_url_name)})}"
        return response

    def get(self, request, *args, **kwargs):
        return self._with_next(super().get(request, *args, **kwargs))

    def form_valid(self, form):
        return self._with_next(super().form_valid(form))
