from django.urls import path

from wagtail.permissions import ModelPermissionPolicy

try:
    from ocyan.main.loading import get_ocyan_class
    SnippetViewSet = get_ocyan_class(
        "wagtail_i18n.wagtailadmin", "SnippetViewSet", module_prefix="ocyan"
    )
except Exception:
    from wagtail.snippets.views.snippets import SnippetViewSet


class ReadOnlyModelPermissionPolicy(ModelPermissionPolicy):
    def user_has_permission(self, user, action):
        if action in ["delete", "add"]:
            return False

        return super().user_has_permission(user, action)


class ReadOnlyIndexView(SnippetViewSet.index_view_class):
    def get_columns(self):
        return super().get_columns()[1:]

    def get_list_buttons(self, instance):  # pylint:disable=unused-argument
        return []


class ReadOnlyInspectView(SnippetViewSet.inspect_view_class):
    def get_edit_url(self):
        return None

    def get_delete_url(self):
        return None


class ReadOnlySnippetViewSet(SnippetViewSet):
    menu_item_is_registered = True
    inspect_view_class = ReadOnlyInspectView
    index_view_class = ReadOnlyIndexView

    @property
    def permission_policy(self):
        return ReadOnlyModelPermissionPolicy(self.model)

    def get_urlpatterns(self):
        urls = super().get_urlpatterns()
        urls[3] = path("inspect/<str:pk>/", self.inspect_view, name="edit")
        return urls
