# Path: posts/models.py
# class Post(Document):
#     author = ReferenceField(User, required=True, reverse_delete_rule=CASCADE)
#     content = StringField(max_length=240, required=True)
# 
#     created_at = DateTimeField(default=datetime.utcnow)
#     updated_at = DateTimeField()
# 
#     def __unicode__(self):
#         return u'{0}'.format(self.content)
# 
# Path: posts/permissions.py
# class IsAuthorOfPost(permissions.BasePermission):
#     def has_object_permission(self, request, view, post):
#         if request.user:
#             return post.author == request.user
#         return False
# 
# Path: posts/serializers.py
# class PostSerializer(serializers.DocumentSerializer):
#     author = UserSerializer(read_only=True, required=False)
# 
#     class Meta:
#         model = Post
#         depth = 1
#         fields = ('id', 'author', 'content', 'created_at', 'updated_at')
#         read_only_fields = ('id', 'created_at', 'updated_at')
# 
# class PostSerializerNonAuth(serializers.DocumentSerializer):
#     """
#     Uses users' serializer for non authenticated requests.
#     Users without email are returned.
#     """
#     author = UserSerializerNonAuth(read_only=True, required=False)
# 
#     class Meta:
#         model = Post
#         depth = 1
#         fields = ('id', 'author', 'content', 'created_at', 'updated_at')
#         read_only_fields = ('id', 'created_at', 'updated_at')


from datetime import datetime
from bson.objectid import ObjectId
from django.apps import apps
from django.shortcuts import Http404
from django.conf import settings
from rest_framework import permissions, status, parsers, renderers
from rest_framework_mongoengine.viewsets import ModelViewSet
from rest_framework.response import Response
from posts.models import Post
from posts.permissions import IsAuthorOfPost
from posts.serializers import PostSerializer, PostSerializerNonAuth
import json

    def get_serializer_class(self):
        """
        Checks if request is authenticated and if not
        send user's info without email field
        :return: Postserializer or PostSerializerNonAuth
        """
        if self.request.user.is_authenticated():
            return PostSerializer
        else:
            return PostSerializerNonAuth

    def get_object(self):
        try:
            post = Post.objects(id=self.kwargs['id'])[0]
        except IndexError:
            raise Http404
        self.check_object_permissions(self.request, post)
        return post

    def list(self, request, *args, **kwargs):
        if request.GET.get('author_id'):
            ds = self.get_serializer_class()(Post.objects(author=ObjectId(request.GET.get('author_id'))).order_by('-created_at'), many=True)
        else:
            ds = self.get_serializer_class()(self.get_queryset().order_by('-created_at'), many=True)
        return Response(ds.data)

    def create(self, request, *args, **kwargs):
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():

# Path: posts/models.py
# class Post(Document):
#     author = ReferenceField(User, required=True, reverse_delete_rule=CASCADE)
#     content = StringField(max_length=240, required=True)
# 
#     created_at = DateTimeField(default=datetime.utcnow)
#     updated_at = DateTimeField()
# 
#     def __unicode__(self):
#         return u'{0}'.format(self.content)
# 
# Path: posts/permissions.py
# class IsAuthorOfPost(permissions.BasePermission):
#     def has_object_permission(self, request, view, post):
#         if request.user:
#             return post.author == request.user
#         return False
# 
# Path: posts/serializers.py
# class PostSerializer(serializers.DocumentSerializer):
#     author = UserSerializer(read_only=True, required=False)
# 
#     class Meta:
#         model = Post
#         depth = 1
#         fields = ('id', 'author', 'content', 'created_at', 'updated_at')
#         read_only_fields = ('id', 'created_at', 'updated_at')
# 
# class PostSerializerNonAuth(serializers.DocumentSerializer):
#     """
#     Uses users' serializer for non authenticated requests.
#     Users without email are returned.
#     """
#     author = UserSerializerNonAuth(read_only=True, required=False)
# 
#     class Meta:
#         model = Post
#         depth = 1
#         fields = ('id', 'author', 'content', 'created_at', 'updated_at')
#         read_only_fields = ('id', 'created_at', 'updated_at')


# Path: posts/views.py
from datetime import datetime
from bson.objectid import ObjectId
from django.apps import apps
from django.shortcuts import Http404
from django.conf import settings
from rest_framework import permissions, status, parsers, renderers
from rest_framework_mongoengine.viewsets import ModelViewSet
from rest_framework.response import Response
from posts.models import Post
from posts.permissions import IsAuthorOfPost
from posts.serializers import PostSerializer, PostSerializerNonAuth
import json


    def get_serializer_class(self):
        """
        Checks if request is authenticated and if not
        send user's info without email field
        :return: Postserializer or PostSerializerNonAuth
        """
        if self.request.user.is_authenticated():
            return PostSerializer
        else:
            return PostSerializerNonAuth

    def get_object(self):
        try:
            post = Post.objects(id=self.kwargs['id'])[0]
        except IndexError:
            raise Http404
        self.check_object_permissions(self.request, post)
        return post

    def list(self, request, *args, **kwargs):
        if request.GET.get('author_id'):
            ds = self.get_serializer_class()(Post.objects(author=ObjectId(request.GET.get('author_id'))).order_by('-created_at'), many=True)
        else:
            ds = self.get_serializer_class()(self.get_queryset().order_by('-created_at'), many=True)
        return Response(ds.data)

    def create(self, request, *args, **kwargs):
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid():

            post = Post(**serializer.validated_data)