import django_filters
from rest_framework import filters
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from spiderhandler.models import QueryJob, QQInfo, WeiboInfo
from spiderhandler.queryrecords.serializers import QueryRecordSerializer, QQInfoSerializer, WeiboInfoSerializer


class QQInfoFilter(filters.FilterSet):
    min_age = django_filters.NumberFilter(name="age", lookup_expr='gte')
    max_age = django_filters.NumberFilter(name="age", lookup_expr='lte')

    class Meta:
        model = QQInfo
        fields = ['qq', 'min_age', 'max_age']


class QQInfoList(APIView):
    """
    List all QQInfo, or create a new QQInfo.
    """

    serializer_class = QQInfoSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = QQInfoFilter

    def get(self, request):

        param = {
            'qq': request.query_params.get('qq', None),
            'min_age': request.query_params.get('min_age', None),
            'max_age': request.query_params.get('max_age', None),
        }
        total = QQInfo.objects.count()
        offset = int(request.query_params.get('offset', 0))
        limit = int(request.query_params.get('limit', total))
        queryset = QQInfo.objects.all()

        if param['qq'] is not None:
            queryset = queryset.filter(qq=param['qq'])
        if param['min_age'] is not None:
            queryset = queryset.filter(age__gte=param['min_age'])
        if param['max_age'] is not None:
            queryset = queryset.filter(age__lte=param['max_age'])
        queryset = queryset[offset:offset + limit]

        serializer = QQInfoSerializer(queryset, many=True)
        return Response(serializer.data)