from django.urls import path
from django.utils.translation import gettext_lazy as _

from oscar.core.loading import get_class

from ocyan.main.loading import get_ocyan_classes

from ocyan.task.models import Task

from .readonly import ReadOnlySnippetViewSet
from .views import cancel, retry

# pylint: disable=W0632
TaskIndexView, TaskInspectView = get_ocyan_classes(
    "task.wagtailadmin.views",
    ["TaskIndexView", "TaskInspectView"],
    module_prefix="ocyan",
)
TaskFilterSet = get_class("task.wagtailadmin.filters", "TaskFilterSet")


class TaskSnippetViewSet(ReadOnlySnippetViewSet):
    model = Task
    menu_label = _("Tasks")
    menu_icon = "doc-full-inverse"
    icon = "doc-full-inverse"
    menu_order = 4
    add_to_admin_menu = True
    inspect_view_class = TaskInspectView
    index_view_class = TaskIndexView
    index_results_template_name = "admin/task/index_results.html"
    inspect_view_fields = [
        "name",
        "status",
        "displayable_logs",
    ]
    filterset_class = TaskFilterSet
    list_display = (
        "__str__",
        "retry_datetime",
        "displayable_status",
        "date_updated",
    )
    search_fields = ("name", "code", "logs__message")

    def get_common_view_kwargs(self, **kwargs):
        return super().get_common_view_kwargs(
            **{
                "retry_url_name": self.get_url_name("retry"),
                "cancel_url_name": self.get_url_name("cancel"),
                "task_url_name": self.get_url_name("edit"),
                **kwargs,
            }
        )

    def get_urlpatterns(self):
        return [
            *super().get_urlpatterns(),
            path("retry/<str:pk>/", self.retry_view, name="retry"),
            path("cancel/<str:pk>/", self.cancel_view, name="cancel"),
        ]

    def retry_view(self, request, pk):
        return retry(request, pk)

    def cancel_view(self, request, pk):
        return cancel(request, pk)
