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 mosquito.api.pagination import PostLimitOffsetPagination, PostPageNumberPagination
from .serializers import SmartListSerializer, SmartPushListSerializer
from ..models import SmartModule, SmartPush


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

    def get_queryset(self, *args, **kwargs):
        queryset_list = SmartModule.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(chip_id__contains=query) |
                Q(region__icontains=query)
            ).distinct()

        return queryset_list


class SmartPushListAPIView(ListAPIView):
    serializer_class = SmartPushListSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [SearchFilter, OrderingFilter]
    pagination_class = PostLimitOffsetPagination
    search_fields = ['smart__name']

    def get_queryset(self, *args, **kwargs):
        queryset_list = SmartPush.objects.all()
        query = self.request.GET.get('q')
        if query:
            queryset_list = queryset_list.filter(
                Q(smart__name__icontains=query)
            ).distinct()

        return queryset_list
