from rest_framework.generics import (
    ListAPIView,
    RetrieveAPIView,
    CreateAPIView
)

from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import SearchFilter, OrderingFilter
from django.db.models import Q
from ..models import Mosquito, MosqPost
from .pagination import PostLimitOffsetPagination, PostPageNumberPagination
from .serializers import MosqListSerializer, MosqPostListSerializer


class MosquitoListAPIView(ListAPIView):
    serializer_class = MosqListSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [SearchFilter, OrderingFilter]
    pagination_class = PostLimitOffsetPagination
    search_fields = ['name', 'device_id', 'region']

    def get_queryset(self, *args, **kwargs):
        queryset_list = Mosquito.objects.all()
        query = self.request.GET.get('q')
        if query:
            queryset_list = queryset_list.filter(
                Q(name__icontains=query) |
                Q(device_id__icontains=query) |
                Q(region__icontains=query)
            ).distinct()
        return queryset_list


class MosquitoPostListAPIView(ListAPIView):
    serializer_class = MosqPostListSerializer
    permission_classes = [IsAuthenticated,]
    filter_backends = [SearchFilter, OrderingFilter]
    pagination_class = PostLimitOffsetPagination
    search_fields = ['mosq__name', 'mosq__region']

    def get_queryset(self, *args, **kwargs):
        queryset_list = MosqPost.objects.all()
        query = self.request.GET.get('q')
        if query:
            queryset_list = queryset_list.filter(
                Q(mosq__name__contains=query) |
                Q(mosq__region=query)
            ).distinct()
        return queryset_list
