from rest_framework import status
from rest_framework import generics
import json
from rest_framework.response import Response
from .serializers import PostSerializer
from .models import Post
from User.models import BasicUser
from User.serializers import SimplifiedUserSerializer, SimplePostSerializer, CommentSerializer

# views


class PostListAllCreateView(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = SimplePostSerializer

    def list(self, request):
        queryset = self.get_queryset()
        if request.query_params.get("topics"):
            topics = json.loads(request.query_params.get("topics"))
            queryset = queryset.filter(topics__contained_by=topics)
        serializer = SimplePostSerializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        data = request.data
        user = None
        if type(data) == type("string"):
            data = json.loads(request.data)
        if request.user.is_authenticated:
            user = BasicUser.objects.get(id=request.user.id)
        serializer = SimplePostSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(user=user)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class PostListView(generics.RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer


class CommentCreateView(generics.CreateAPIView):
    serializer_class = CommentSerializer

    def create(self, request, *args, **kwargs):
        data = request.data
        user = None
        if type(data) == type("string"):
            data = json.loads(request.data)
        post_id = request.path.split("/")[2]
        data["post"] = post_id
        if request.user.is_authenticated:
            user = BasicUser.objects.get(id=request.user.id)
        serializer = CommentSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(user=user)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
