from django.shortcuts import render
from django.views.generic import FormView, ListView
from django.views.generic.base import TemplateView

from common.utils.utils import filter_queryset_by_user
from containers.forms import ContainerSearchForm
from containers.models import Container


# class ContainerDetails(FormView):
#     template_name = 'common/container-details.html'
#     form_class = ContainerSearchForm
#     model = Container
#     base_template = 'employee-base.html'
#     context_object_name = 'objects'
#     paginate_by = 10
#
#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context['base_template'] = self.base_template
#         return context
#
#     def get(self, request, *args, **kwargs):
#
#         referrer = request.META.get('HTTP_REFERER', '')
#         if 'container-details' not in referrer:
#             request.session.pop('container_number', None)
#
#
#         context = self.get_context_data()
#         selected_id = request.GET.get('selected')
#         container_number = request.session.get('container_number')
#
#         if container_number:
#             containers = Container.objects.filter(number=container_number).order_by('-received_on')
#             if containers.exists():
#                 if selected_id:
#                     try:
#                         selected_container = containers.get(id=selected_id)
#                     except Container.DoesNotExist:
#                         selected_container = containers.first()
#                 else:
#                     selected_container = containers.first()
#
#                 context.update({
#                     'form': self.form_class(initial={'container_number': container_number}),
#                     'container': selected_container,
#                     'objects': containers,  # For list-crud.html compatibility
#                     'show_results': True
#                 })
#                 return render(request, self.template_name, context)
#
#         context.update({
#             'form': self.form_class(),
#             'show_results': False
#         })
#         return render(request, self.template_name, context)
#
#     def form_valid(self, form):
#         container_number = form.cleaned_data['container_number']
#         self.request.session['container_number'] = container_number  # Store in session
#         context = self.get_context_data()
#         containers = Container.objects.filter(number=container_number).order_by('-received_on')
#         if containers.exists():
#             context.update({
#                 'form': form,
#                 'container': containers.first(),
#                 'objects': containers,  # For list-crud.html compatibility
#                 'show_results': True
#             })
#         else:
#             context.update({
#                 'form': form,
#                 'error': 'Container not found',
#                 'show_results': False
#             })
#         return render(self.request, self.template_name, context)


class ContainerDetails(ListView):
    template_name = 'common/container-details.html'
    model = Container
    # base_template = 'employee-base.html'
    context_object_name = 'objects'
    paginate_by = 10

    def get_queryset(self):
        container_number = self.request.session.get('container_number')
        if container_number:
            query = Container.objects.filter(number=container_number).order_by('-received_on')
            query = filter_queryset_by_user(query, self.request.user)
            return query

        return Container.objects.none()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # context['base_template'] = self.base_template
        context['form'] = ContainerSearchForm(
            initial={'container_number': self.request.session.get('container_number')}
        )

        full_queryset = self.get_queryset()
        if full_queryset.exists():
            selected_id = self.request.GET.get('selected')
            if selected_id:
                try:
                    context['container'] = full_queryset.get(id=selected_id)
                except Container.DoesNotExist:
                    context['container'] = full_queryset.first()
            else:
                context['container'] = full_queryset.first()
            context['show_results'] = True
        else:
            context['show_results'] = False

        return context

    def post(self, request, *args, **kwargs):
        form = ContainerSearchForm(request.POST)
        if form.is_valid():
            container_number = form.cleaned_data['container_number']
            request.session['container_number'] = container_number
            return self.get(request, *args, **kwargs)

        context = self.get_context_data()
        context['form'] = form
        context['show_results'] = False
        return render(request, self.template_name, context)