from rest_framework import generics, permissions


from .serializers import UserSerializer, PostSerializer, PhotoSerializer
from .models import User, Post, Photo
from .permissions import PostAuthorCanEditPermission


class UserList(generics.ListAPIView):
    model = User
    serializer_class = UserSerializer
    permission_classes = [
        permissions.AllowAny
    ]

    def get_queryset(self):
        return User.objects.all()

class UserDetail(generics.RetrieveAPIView):
    model = User
    serializer_class = UserSerializer
    lookup_field = 'username'


class PostMixin(object):
    model = Post
    serializer_class = PostSerializer

    permission_classes = [
        PostAuthorCanEditPermission
    ]

    def pre_save(self, obj):
        """Force author to the current user on save"""
        obj.author = self.request.user
        return super(PostMixin, self).pre_save(obj)

    def get_queryset(self):
        return Post.objects.all()


class PostList(PostMixin, generics.ListCreateAPIView):
    pass

class PostDetail(PostMixin, generics.RetrieveUpdateDestroyAPIView):
    pass


class UserPostList(generics.ListAPIView):
    model = Post
    serializer_class = PostSerializer

    def get_queryset(self):
        queryset = super(UserPostList, self).get_queryset()
        return queryset.filter(author__username=self.kwargs.get('username'))


class PhotoList(generics.ListCreateAPIView):
    model = Photo
    serializer_class = PhotoSerializer
    permission_classes = [
        permissions.AllowAny
    ]

    def get_queryset(self):
        return Photo.objects.all()

class PhotoDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Photo
    serializer_class = PhotoSerializer
    permission_classes = [
        permissions.AllowAny
    ]


class PostPhotoList(generics.ListAPIView):
    model = Photo
    serializer_class = PhotoSerializer

    def get_queryset(self):
        return Photo.objects.all()
        # queryset = super(PostPhotoList, self).get_queryset()
        # return queryset.filter(post__pk=self.kwargs.get('pk'))
