from django.db.models import Prefetch

from rest_framework import status
from rest_framework.generics import (
    GenericAPIView,
    ListAPIView,
    RetrieveUpdateAPIView,
    get_object_or_404,
)
from rest_framework.response import Response

from newsreader.core.pagination import CursorPagination
from newsreader.news.collection.models import CollectionRule
from newsreader.news.collection.serializers import RuleSerializer
from newsreader.news.core.models import Post
from newsreader.news.core.serializers import PostSerializer


class DetailRuleView(RetrieveUpdateAPIView):
    queryset = CollectionRule.objects.all()
    serializer_class = RuleSerializer


class NestedRuleView(ListAPIView):
    queryset = CollectionRule.objects.prefetch_related("posts").all()
    serializer_class = PostSerializer
    pagination_class = CursorPagination

    def get_queryset(self):
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        # Default permission is IsOwner, therefore there shouldn't have to be
        # filtered on the user.
        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}

        prefetch = Prefetch("posts", queryset=Post.objects.filter(read=False))
        queryset = CollectionRule.objects.prefetch_related(prefetch)
        rule = get_object_or_404(queryset, **filter_kwargs)
        self.check_object_permissions(self.request, rule)

        return rule.posts.order_by("-publication_date")


class RuleReadView(GenericAPIView):
    queryset = CollectionRule.objects.all()
    serializer_class = RuleSerializer

    def post(self, request, *args, **kwargs):
        rule = self.get_object()

        Post.objects.filter(rule=rule).update(read=True)

        rule.refresh_from_db()
        serializer_class = self.get_serializer_class()
        serializer = serializer_class(rule)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
