from django.contrib.auth.mixins import UserPassesTestMixin
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.views import generic

from ..forms import ItemCreateForm
from ..models import GroupedOrder, Item


class ItemCreateView(UserPassesTestMixin, generic.CreateView):
    model = Item
    form_class = ItemCreateForm

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["grouped_order"] = GroupedOrder.objects.get(code=self.kwargs.get("code"))
        return kwargs

    def test_func(self):
        # Restrict access to the manager
        grouped_order = get_object_or_404(GroupedOrder, code=self.kwargs.get("code"))
        return grouped_order.orga == self.request.user


class ItemDeleteView(UserPassesTestMixin, generic.DeleteView):
    model = Item

    def get_success_url(self):
        return reverse_lazy("order:manage_items", args=[self.object.grouped_order.code])

    def test_func(self):
        # Restrict access to the manager or a superuser
        return (
            self.get_object().grouped_order.orga == self.request.user
            or self.request.user.is_superuser
        )
