from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms import forms
from django.forms.widgets import HiddenInput
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import TemplateView, FormView, CreateView

from common.utils import filter_queryset_by_user, get_preinfo_by_number
from preinfo.forms import PreinfoBaseForm, PreinfoCreateForm
from preinfo.models import Preinfo



class ClientPreinfoView(LoginRequiredMixin, CreateView):
    template_name = 'client-preinfo-content.html'
    form_class = PreinfoCreateForm
    success_url = reverse_lazy('client_preinfo')
    model = Preinfo

    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 #form.fields['line'].widget.attrs['disabled'] = True
            # Keep the value when form is submitted
            # form.fields['line'].widget = HiddenInput()

        return form


    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)


#     Check if a preinfo exists for the given container number
def check_preinfo(request):
    number = request.GET.get('number')
    preinfo = Preinfo.objects.filter(container_number=number, received=False).first()
    if preinfo:
        return JsonResponse({
            'found': True,
            'line': preinfo.line.name,
            'container_type': preinfo.container_type.name,
            'preinfo_id': preinfo.id,
        })
    return JsonResponse({'found': False})


class PreinfoSearchView(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')

        preinfo = get_preinfo_by_number(number)
        if preinfo:
            next_url = request.POST.get('param')
            return redirect(next_url, pk=preinfo.pk)

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