from django.urls import path

from wagtail.admin.widgets.button import HeaderButton

from ocyan.main.loading import get_ocyan_class

from .views import OrderingEditView, OrderingIndexView

SnippetViewSet = get_ocyan_class("wagtail_i18n.wagtailadmin", "SnippetViewSet")
ModelViewSet = get_ocyan_class("wagtail_i18n.wagtailadmin", "ModelViewSet")


class OrderableViewSetMixin:
    def get_urlpatterns(self):
        urls = super().get_urlpatterns() + [
            path("ordering/", self.ordering_view, name="ordering"),
            path("ordering/update/", self.ordering_update_view, name="ordering-update"),
        ]
        return urls

    def get_index_view_kwargs(self, **kwargs):
        kwargs = super().get_index_view_kwargs(**kwargs)
        header_more_buttons = kwargs.get("header_more_buttons", [])
        header_more_buttons.append(
            HeaderButton(
                label="Order",
                url="ordering/",
                icon_name="arrow-down",
            )
        )
        kwargs["header_more_buttons"] = header_more_buttons
        return kwargs

    def ordering_view(self, request):
        view = OrderingIndexView.as_view(model=self.model)
        return view(request)

    def ordering_update_view(self, request):
        view = OrderingEditView.as_view(model=self.model)
        return view(request)


class OrderableModelViewSet(OrderableViewSetMixin, ModelViewSet):
    pass


class OrderableSnippetViewSet(OrderableViewSetMixin, SnippetViewSet):
    pass
