from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, ListView

from DepoT.mixins.LineFiltweFormMixin import LineFilterFormMixin
from booking.forms import BookingCreateForm, BookingUpdateForm
from booking.models import Booking
from common.utils.utils import filter_queryset_by_user


class ClientBookingView(LoginRequiredMixin, UserPassesTestMixin, ListView):
    model = Booking
    template_name = 'client/booking-list.html'
    paginate_by = 4
    context_object_name = 'objects'
    # base_template = 'client-base.html'

    def test_func(self):
        return self.request.user.has_company_perm('can_view_booking') or self.request.user.user_type == 'CA'

    # def get_context_data(self, **kwargs):
    #     context = super().get_context_data(**kwargs)
    #     context['base_template'] = self.base_template
    #     return context

    def get_queryset(self):
        queryset = super().get_queryset()
        user = self.request.user
        result = filter_queryset_by_user(queryset, user)
        return result


class CreateBookingView(LoginRequiredMixin, UserPassesTestMixin, LineFilterFormMixin, CreateView):
    template_name = 'client/booking-create.html'
    model = Booking
    form_class = BookingCreateForm
    success_url = reverse_lazy('client_booking')

    def form_valid(self, form):
        # todo more validation
        form.instance.created_by = self.request.user.id
        form.instance.updated_by = self.request.user.id
        form.instance.vehicles_left = form.cleaned_data.get('vehicles')
        return super().form_valid(form)

    def test_func(self):
        return True # self.request.user.has_company_perm('can_edit_preinfo') or self.request.user.user_type == 'CA'


class ClientBookingUpdateView(LoginRequiredMixin, UserPassesTestMixin, LineFilterFormMixin, CreateView):
    template_name = 'client/booking-edit.html'
    model = Booking
    form_class = BookingUpdateForm
    success_url = reverse_lazy('client_booking')

    def form_valid(self, form):
        # todo more validation
        form.instance.updated_by = self.request.user.id
        return super().form_valid(form)

    def test_func(self):
        return True # self.request.user.has_company_perm('can_edit_preinfo') or self.request.user.user_type == 'CA'