from django.contrib.admin.utils import quote
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse

from wagtail.core.hooks import search_for_hooks

"""
A mechanism for finding the admin edit URL for an arbitrary object instance, optionally applying
permission checks.

    url_finder = AdminURLFinder(request.user)
    url_finder.get_edit_url(some_page)  # => "/admin/pages/123/edit/"
    url_finder.get_edit_url(some_image)  # => "/admin/images/456/"
    url_finder.get_edit_url(some_site)  # => None (user does not have edit permission for sites)

If the user parameter is omitted, edit URLs are returned without considering permissions.

Handlers for new models can be registered via register_admin_url_finder:

    class SprocketAdminURLFinder(ModelAdminURLFinder):
        edit_url_name = 'wagtailsprockets:edit'

    register_admin_url_finder(Sprocket, SprocketAdminURLFinder)
"""


class ModelAdminURLFinder:
    """
    Handles admin edit URL lookups for an individual model
    """

    edit_url_name = None
    permission_policy = None

    def __init__(self, user=None):
        self.user = user

    def construct_edit_url(self, instance):
        """
        Return the edit URL for the given instance - regardless of whether the user can access it -
        or None if no edit URL is available.
        """
        if self.edit_url_name is None:
            raise ImproperlyConfigured(
                "%r must define edit_url_name or override construct_edit_url"
                % type(self)
            )
        return reverse(self.edit_url_name, args=(quote(instance.pk),))

    def get_edit_url(self, instance):
        """
        Return the edit URL for the given instance if one exists and the user has permission for it,
        or None otherwise.
        """
        if (
            self.user
            and self.permission_policy
            and not self.permission_policy.user_has_permission_for_instance(
                self.user, "change", instance
            )
        ):
            return None
        else:
            return self.construct_edit_url(instance)


class NullAdminURLFinder:
    """
    A dummy AdminURLFinder that always returns None
    """

    def __init__(self, user=None):
        pass

    def get_edit_url(self, instance):
        return None


FINDER_CLASSES_BY_MODEL = {}


def register_admin_url_finder(model, handler):
    global FINDER_CLASSES_BY_MODEL
    FINDER_CLASSES_BY_MODEL[model] = handler


class AdminURLFinder:
    """
    The 'main' admin URL finder, which searches across all registered models
    """

    def __init__(self, user=None):
        search_for_hooks()  # ensure wagtail_hooks files have been loaded
        self.user = user
        self.finders_by_model = {}

    def get_edit_url(self, instance):
        model = type(instance)
        try:
            # do we already have a finder for this model and user?
            finder = self.finders_by_model[model]
        except KeyError:
            finder_class = NullAdminURLFinder
            # check all superclasses of model for a registered finder class
            for cls in model.__mro__:
                try:
                    finder_class = FINDER_CLASSES_BY_MODEL[cls]
                    break
                except KeyError:
                    continue

            finder = finder_class(self.user)
            self.finders_by_model[model] = finder

        return finder.get_edit_url(instance)

@@ -174,16 +174,70 @@
 or_hooks
+%0Afrom wagtail.utils.registry import ObjectTypeRegistry
 %0A%0A%22%22%22%0AA 
@@ -2388,36 +2388,45 @@
 e%0A%0A%0A
-FINDER_CLASSES_BY_MODEL = %7B%7D
+finder_classes = ObjectTypeRegistry()
 %0A%0A%0Ad
@@ -2479,83 +2479,53 @@
     
-global FINDER_CLASSES_BY_MODEL%0A    FINDER_CLASSES_BY_MODEL%5Bmodel%5D = 
+finder_classes.register(model, value=
 handler
+)
 %0A%0A%0Ac
@@ -3064,314 +3064,58 @@
 s = 
-NullAdminURLFinder%0A            # check all superclasses of model for a registered finder class%0A            for cls in model.__mro__:%0A                try:%0A                    finder_class = FINDER_CLASSES_BY_MODEL%5Bcls%5D%0A                    break%0A                except KeyError:%0A                    continue%0A
+finder_classes.get(instance) or NullAdminURLFinder
 %0A   

Use ObjectTypeRegistry for AdminURLFinder