from warnings import filters
from django.shortcuts import render
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import JSONParser,ParseError
from rest_framework import status
from rest_framework import generics
from . import engine
import threading
import django_filters.rest_framework
from rest_framework.decorators import action
from django.conf import settings
from django.shortcuts import get_object_or_404


from . import models
from . import serializers

eng = 0
lock = threading.Lock()

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = serializers.UserSerializer
    permission_classes = [permissions.IsAuthenticated]

class device_ViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = models.device.objects.all().order_by('-time_creation',)
    serializer_class = serializers.device_Serializer
    permission_classes = [permissions.IsAuthenticated]

    filtred_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ['device_type', 'brend', 'serial_model']



class measurement_info_Viewset(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = models.measurement_info.objects.all().order_by('-id',)
    serializer_class = serializers.measurement_info_Serializer
    permission_classes = [permissions.IsAuthenticated]

    filtred_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ['id', 'infostr']

class state_Viewset(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = models.state.objects.all().order_by('-id',)
    serializer_class = serializers.state_Serializer
    permission_classes = [permissions.IsAuthenticated]

    filtred_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ['id_measurement']
        
class measurement_ViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = models.measurement.objects.all().order_by('-id',)
    serializer_class = serializers.measurement_post_Serializer
    permission_classes = [permissions.IsAuthenticated]

    #filtred_backends = [django_filters.rest_framework.DjangoFilterBackend]
    #filterset_fields = ['id']

    @action(methods=['get'], detail=True, permission_classes=[permissions.IsAuthenticated],
            url_path='data', url_name='data')
    def data(self, request, pk=None):
        try:
            measurement = models.measurement.objects.get(id=pk)
        except models.measurement.DoesNotExist:
            return Response(
                {
                    "status": f"Measurement {pk} does not exist!"
                },
                status=status.HTTP_404_NOT_FOUND,
            )
        if(measurement.state.data_ready != True):
            return Response(
                {
                    "status": "Data isn't ready!"
                },
                status=status.HTTP_403_FORBIDDEN,
            )
        data_num = request.GET.get('data_num', None)
        averaging_num = request.GET.get('averaging_num', None)

        if(data_num == None):
            if(averaging_num == None):
                queryset = models.measurement_data.objects.filter(measurement_id=pk).order_by('-id',)
            else:
                queryset = models.measurement_data.objects.filter(measurement_id=pk, averaging_num=averaging_num).order_by('-id',)
        else:
            if(averaging_num == None):
                queryset = models.measurement_data.objects.filter(measurement_id=pk, data_num=data_num).order_by('-id',)
            else:
                queryset = models.measurement_data.objects.filter(measurement_id=pk, data_num=data_num, averaging_num=averaging_num).order_by('-id',)
        serializer = serializers.measurement_data_Serializer(queryset, many=True)
        return Response(serializer.data)

    @action(methods=['get'], detail=True, permission_classes=[permissions.IsAuthenticated],
            url_path='state', url_name='state')
    def state(self, request, pk=None):
        queryset = models.measurement.objects.all().order_by('-id',)
        measurement = get_object_or_404(queryset, id=pk)
        serializer = serializers.state_Serializer(measurement.state)
        return Response(serializer.data)

    @action(methods=['get'], detail=True, permission_classes=[permissions.IsAuthenticated],
            url_path='info', url_name='info')
    def info(self, request, pk=None):
        queryset = models.measurement.objects.all().order_by('-id',)
        measurement = get_object_or_404(queryset, id=pk)
        serializer = serializers.measurement_info_Serializer(measurement.info)
        return Response(serializer.data)
    
    def create(self, request, *args, **kwargs):
        serializer = serializers.measurement_post_Serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        #state_ser = serializers.state_Serializer(state)

        # Сохранение объекта (ID инкрементируется автоматически)

        adc = models.device_state.objects.create()
        sync = models.device_state.objects.create()
        sdr = models.device_state.objects.create()
        grax = models.device_state.objects.create()
        gray = models.device_state.objects.create()
        graz = models.device_state.objects.create()

        self.perform_create(serializer)
        mid = serializer.data['id']
        instance = models.measurement.objects.get(id=mid)
        instance.state = models.state.objects.create(id_measurement=mid, adc=adc, sync=sync, sdr=sdr, grax=grax, gray=gray, graz=graz)
        print(settings.BASE_DIR)
        instance.save()

        eng = engine.EngineDict[instance.info.engine](instance, lock)
        
        # Форматирование ответа
        headers = self.get_success_headers(serializer.data)
        return Response(
            {
                "status": "created",
                "measurement_id": mid,
                "basedir": str(settings.BASE_DIR)
            },
            status=status.HTTP_201_CREATED,
            headers=headers
        )
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        instance.state.delete()
        instance.info.delete()
        instance.info.iadc.delete()
        instance.info.isync.delete()
        instance.info.isdr.delete()
        instance.info.igrax.delete()
        instance.info.igray.delete()
        instance.info.igraz.delete()
        instance.state.adc.delete()
        instance.state.sync.delete()
        instance.state.sdr.delete()
        instance.state.grax.delete()
        instance.state.gray.delete()
        instance.state.graz.delete()
        
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

class measurement_data_ViewSet(viewsets.ModelViewSet):
    queryset = models.measurement_data.objects.all().order_by('-id',)
    serializer_class = serializers.measurement_data_Serializer
    permission_classes = [permissions.IsAuthenticated]

    filtred_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields = ['measurement__id', 'data_num', 'averaging_num']

# Create your views here.
def post_list(request):
    return render(request, 'adc_interface/index.html', {})