from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView

from booking.forms import BookingCreateForm
from booking.models import Booking
from common.utils import filter_queryset_by_user


# Create your views here.
class CreateBookingView(CreateView):
    template_name = 'client-booking-content.html'
    model = Booking
    form_class = BookingCreateForm
    success_url = reverse_lazy('client_booking')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        queryset = self.model.objects.all().order_by('-created_on')
        user = self.request.user
# !!! important
        queryset = filter_queryset_by_user( queryset, user)[:10]
# !!! important
        context['recent'] = queryset
        return context

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        user = self.request.user

        # If user has a specific line, limit the line choices
        if user.line:
            form.fields['line'].queryset = form.fields['line'].queryset.filter(pk=user.line.pk)
            form.fields['line'].initial = user.line
            form.fields['line'].widget.readonly = True   #attrs['disabled'] = True
        return form

    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')
        if self.request.user.line:
            form.instance.line = self.request.user.line
        return super().form_valid(form)