from datetime import timezone

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.utils.timezone import now
from django.views import View
from django.views.generic import CreateView, ListView, UpdateView
from rest_framework.generics import get_object_or_404

from DepoT.mixins.LineFiltweFormMixin import LineFilterFormMixin
from common.utils.utils import filter_queryset_by_user, get_preinfo_by_number, send_test_email
from payments.services import EPay
from preinfo.forms import PreinfoCreateForm, PreinfoEditForm
from preinfo.models import Preinfo


class ClientPreinfoView(LoginRequiredMixin, UserPassesTestMixin, ListView):

# ListView
    model = Preinfo
    template_name = 'client/preinfo-list.html'
    paginate_by = 4

# CRUDListView template
    context_object_name = 'objects'
    # base_template = 'client-base.html'

    def test_func(self):
        return self.request.user.has_company_perm('can_view_preinfo') 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 ClientPreinfoCreateView(LoginRequiredMixin, UserPassesTestMixin, LineFilterFormMixin, CreateView):
    model = Preinfo
    template_name = 'client/preinfo-create.html'
    form_class = PreinfoCreateForm
    success_url = reverse_lazy('client_preinfo')

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

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



class ClientPreinfoUpdateView(LoginRequiredMixin, UserPassesTestMixin, LineFilterFormMixin, UpdateView):
    model = Preinfo
    template_name = 'client/preinfo-edit.html'
    form_class = PreinfoEditForm
    success_url = reverse_lazy('client_preinfo')

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

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

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'})


class ClientPreinfoDeleteView(LoginRequiredMixin, UserPassesTestMixin, View):
    success_url = reverse_lazy('client_preinfo')

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

    def post(self, request, pk, *args, **kwargs):
        target_preinfo = get_object_or_404(Preinfo, pk=pk)
        if target_preinfo.received:
            return JsonResponse({'success': False, 'error': 'Cannot delete completed preinfo.'})
        if target_preinfo.deleted:
            return JsonResponse({'success': False, 'error': 'Preinfo already deleted.'})
        target_preinfo.deleted = True
        target_preinfo.deleted_on = now()
        target_preinfo.deleted_by = request.user
        target_preinfo.save()
        return JsonResponse({'success': True, 'is_active': target_preinfo.active})