from django.db import transaction
from django.db.models import Case, When
from django.http import JsonResponse
from django.utils.functional import cached_property

from wagtail.admin.views.generic import EditView, IndexView

from .columns import OrderableColumn


class OrderingIndexView(IndexView):
    template_name = "wagtailadmin/orderable/orderable_listing.html"

    def get_ordering(self):
        return getattr(self.model, "sort_order_field", "sort_order")

    @cached_property
    def columns(self):
        columns = super().columns
        columns = [OrderableColumn(name="")] + columns
        return columns


class OrderingEditView(EditView):
    def get_ordering(self):
        return getattr(self.model, "sort_order_field", "sort_order")

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            ordered_ids = request.POST.getlist("items[]")
            ordered_ids = [int(id_) for id_ in ordered_ids]
        except (KeyError, ValueError):
            return JsonResponse({"error": "Invalid data format"}, status=400)

        order_cases = [
            When(id=id_, then=order) for order, id_ in enumerate(ordered_ids)
        ]
        self.model.objects.filter(id__in=ordered_ids).update(
            **{self.get_ordering(): Case(*order_cases)}
        )
        return JsonResponse({"status": "success"})
