from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import CreateView, UpdateView, FormView

from common.utils import get_container_by_number
from containers.forms import ContainerReceiveForm, ContainerExpeditionForm
from containers.models import Container
from preinfo.models import Preinfo


# Create your views here.
class ContainerReceive(CreateView):
    template_name = 'container-receive.html'
    model = Container
    form_class = ContainerReceiveForm
    success_url = reverse_lazy('dashboard')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pk = self.kwargs.get('pk')
        try:
            preinfo =Preinfo.objects.filter(pk=pk, received=False).first()
        except Preinfo.DoesNotExist:
            preinfo = None

        if preinfo:
            context['preinfo'] = preinfo
            context['containers'] = Container.objects.order_by('-received_on').all()[:10]  # Fetch the last 10 containers
            return context
        return redirect(reverse_lazy('container_search'))

    def form_valid(self, form):

        # Get the preinfo_id from the POST data
        preinfo_id = self.request.POST.get('preinfo_id')
        try:
            preinfo = Preinfo.objects.get(id=preinfo_id)
        except Preinfo.DoesNotExist:
            preinfo = None

        # validate if data is correct, comparing user data with preinfo data
        if preinfo and preinfo.container_number == form.cleaned_data.get('number') and not preinfo.received:
            preinfo.received = True
            preinfo.save()

            form.instance.received_by = self.request.user
            form.instance.line = preinfo.line
            form.instance.container_type = preinfo.container_type
        else:
            form.add_error('number', 'Invalid data')

        return super().form_valid(form)


class ContainerSearchView(View):
    template_name = 'container-search.html'

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request):
        number = request.POST.get('number')
        container = get_container_by_number(number)
        if container:
            if container.booking:
                next_url = request.POST.get('param')
                return redirect(next_url, pk=container.booking.pk)
            else:
                return render(request, self.template_name, {'error': 'Booking not found'})

        return render(request, self.template_name, {'error': 'Not found'})


class ContainerExpedition(UpdateView):
    template_name = 'container-expedition.html'
    model = Container
    form_class = ContainerExpeditionForm
    success_url = reverse_lazy('dashboard')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pk = self.kwargs.get('pk')
        try:
            preinfo =Preinfo.objects.filter(pk=pk, received=False).first()
        except Preinfo.DoesNotExist:
            preinfo = None

        if preinfo:
            context['preinfo'] = preinfo
            context['containers'] = Container.objects.order_by('-received_on').all()[:10]  # Fetch the last 10 containers
            return context
        return redirect(reverse_lazy('container_search'))





