from dbsynce.models import Resource
from webservice_running.models import ResourceLocal
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import JsonResponse
from django.utils.translation import gettext as _
from django_tables2 import SingleTableView
from django.views.generic import DetailView
from django.views.generic import UpdateView


from django.shortcuts import render
from django.http import Http404
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect


from webservice_running.tables import ResourcesLocalTable
from sharix_admin.utils import group_required


from datetime import datetime, timedelta
from dbsynce.lib.core import parse_requirements, get_admin_url
from dbsynce.models import Documents
from django.contrib import messages
from django.db import transaction
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from django.views.generic.edit import CreateView
from tickets.models import Ticket, TicketList

from webservice_running.forms import ResourceLocalForm
from sharix_admin.forms import ResourceForm
from sharix_admin.utils import *
from dbsynce.lib.data import *
from sharix_admin.views.base import BaseView
from webservice_running.views.base_local import BaseLocalView
from django.db.models import Q

from django import forms
from django.shortcuts import redirect

from dbsynce.docs.database.resource import Resource as ResourceHelpTexts
from dbsynce.docs.verbose_names.resource import Resource as ResourceVerboseNames

from webservice_running.docs.database.local import Local as HelpTextsLocal
from webservice_running.docs.verbose_names.local import Local as VerboseNameLocal


class ResourcesLocalListView(BaseView, UserPassesTestMixin, SingleTableView):
    table_class = ResourcesLocalTable
    queryset = ResourceLocal.objects.all()
    template_name = 'webservice_running/local/resource_local_list.html'
    page_title = 'Локальные данные ресурсов'
    page_name = 'resources'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'title': self.page_title,
            'object_list': context['object_list'],
        })
        return context

    def get_queryset(self):
        queryset = super().get_queryset()
        search_query = self.request.GET.get('q', '').strip()
        if search_query:
            queryset = queryset.filter(
                Q(id__icontains=search_query) |
                Q(user__first_name__icontains=search_query) |
                Q(user__last_name__icontains=search_query) |
                Q(status__icontains=search_query)
            ).distinct()
        return queryset

    def test_func(self) -> bool or None:
        #group_names = ('PARTNER-ADMIN')
        #if bool(self.request.user.groups.filter(name=group_names)) or self.request.user.is_superuser:
        #    return True
        #return False
        return True


@login_required
@group_required('PARTNER-ADMIN')
def change_resource_status(request):
    if request.method == 'POST':
        resource = request.POST.get('resource')
        new_status = request.POST.get('new_status')

        resource = Resource.objects.get(pk=resource)
        resource.status = new_status
        resource.save()
        return JsonResponse({'status': 'success'})
    else:
        return JsonResponse({'status': 'error'})

#class ResourceLocalEditView(BaseLocalView, FormView):
class ResourceLocalEditView(BaseView, UpdateView):
    #form_base = ResourceForm
    #form_local = ResourceLocalForm
    form_class = ResourceLocalForm
    model = ResourceLocal
    template_name = "webservice_running/local/resource_local_edit.html"
    success_url = reverse_lazy("webservice_running:resources_local")
    page_title = 'Изменить ресурс c локальными данными'
    page_name = 'resource_local_edit'

    # Проверяем состояит ли текущий пользователь в группе PARTNER-ADMIN
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['instance'] = get_object_or_404(ResourceLocal, id=self.object.id)
        return kwargs

    def form_valid(self, form):
        with transaction.atomic():
            # Сохраняем изменения
            form.save()

            # Получаем текущий объект компании и деактивируем ее
            current_local_resource = form.instance
            #current_local.deactivate()
            current_local_resource.resource.deactivate()

            # Выполняем пересоздание тикета на активацию партнера
            #TODO - тикет для партнера?
            current_local_resource.resource.ticket_status.archive()
            current_local_resource.resource.ticket_status = create_ticket_resource_activation_by_metaservice_supervisor(self.request.user, current_local_resource.resource)

        # Отправляем полAьзователю уведомление на страницу об успехе операции
        messages.success(self.request, 'Данные успешно изменены и теперь проходят проверку!')
        return super().form_valid(form)



class ResourceLocalCreate(BaseLocalView):

    form_base = ResourceForm
    form_local = ResourceLocalForm

    #resource_form = ResourceForm
    #resource_local_form = ResourceLocalForm
    template_name = "webservice_running/local/resource_local.html"
    success_url = reverse_lazy("webservice_running:main_local")
    page_title = 'Добавить ресурс с локальными данными'
    page_name = 'resource_local/add/'

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context.update({'form_base': self.form_base(prefix='form_base'), 'form_local': self.form_local(prefix='form_local')})
        return render(
            request,
            self.template_name,
            context,
        )

    def post(self, request, *args, **kwargs):

        form_base = self.form_base(request.POST, prefix='form_base')
        form_local = self.form_local(request.POST, prefix='form_local')

        if form_local.is_valid() and form_base.is_valid():

            instance=form_base.save(commit=False)
            instance.user = self.request.user
            instance.save()
            instance.ticket_status = create_ticket_resource_activation_by_metaservice_supervisor(self.request.user, instance)
            create_ticket_resource_activation_by_partner_admin(self.request.user, instance)
            
            instance.save()

            doc_codes = parse_requirements(instance.requirements)
            Documents.objects.bulk_create([
                Documents(
            #        #TODO add info about company
                    resource=instance,
                    user=self.request.user,
                    doc_type=doc_code
                ) for doc_code in doc_codes
                ])

            messages.success(
                self.request,
                'Ваша заявка на добавление ресурса успешно отправлена и теперь проходит проверку!'
                )
            instance_local=form_local.save(commit=False)
            instance_local.resource=instance
            form_local.save()
            return redirect(self.success_url)
        else:
            
            context = self.get_context_data(**kwargs)
            context.update({'form_base': self.form_base(prefix='form_base'), 'form_local': self.form_local(prefix='form_local')})
            messages.error(
                'Возникла ошибка, попробуйте снова!')

        
        context = self.get_context_data(**kwargs)
        
        context.update({'form_base': self.form_base(prefix='form_base'), 'form_local': self.form_local(prefix='form_local')})
        return render(
            request,
            self.template_name,
            context,
        )



class ResourceLocalDetailView(BaseView, DetailView):
    model = ResourceLocal
    template_name = 'webservice_running/local/resource_local_detail.html'
    context_object_name = 'resource_local'
    page_title = 'Локальная информация о ресурсе'
    page_name = 'resource_local_detail'

    def detail_view(self, request, primary_key):

        try:
            resource_local = ResourceLocal.objects.get(pk=primary_key)
            #docs = Documents.objects.filter(resource=self.object.resource)
            #context['docs'] = self.docs
        except ResourceLocal.DoesNotExist:
            #docs=[]
            raise Http404('Something does not exist')
            

        return render(request, self.template_name, context={
            })

    def get_context_data(self, **kwargs):
        try:
            docs = Documents.objects.filter(resource=self.object.resource)
        except Documents.DoesNotExist:
            docs=[]
        context = super().get_context_data(**kwargs)
        context['help_texts'] = ResourceHelpTexts
        context['captions'] = ResourceVerboseNames
        context['help_texts_local'] = HelpTextsLocal
        context['captions_local'] = VerboseNameLocal
        context['docs'] = docs
        return context
