# Path: voting_app/polls/models.py
# class Question(models.Model):
#     author = models.ForeignKey(User, related_name='questions')
#     question_text = models.CharField(max_length=300)
#     created_date = models.DateTimeField(auto_now_add=True)
#     updated_date = models.DateTimeField(auto_now=True)
# 
#     class Meta:
#         ordering = ['-created_date']
# 
#     def __str__(self):
#         return self.question_text 
# 
# class Choice(models.Model):
#     question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE)
#     choice_text = models.CharField(max_length=200)
#     vote = models.PositiveIntegerField(db_index=True, default=0)
# 
#     def __str__(self):
#         return self.choice_text
# 
# class Vote(models.Model):
#     question = models.ForeignKey(Question, related_name='votes', on_delete=models.CASCADE)
#     vote_author = models.ForeignKey(User, related_name='votes', blank=True, null=True)
#     voter_ip = models.GenericIPAddressField(blank=True, null=True, db_index=True)
#     choice = models.ForeignKey(Choice, related_name='votes')
#     created_date = models.DateTimeField(auto_now_add=True)
# 
#     class Meta:
#         index_together = [
#             ["question", "vote_author"],
#             ["question", "voter_ip"],
#         ]
# 
# Path: voting_app/polls/api/serializers.py
# class QuestionSerializer(serializers.ModelSerializer):
# 
#     choices = ChoicesSerializerWithVote(many=True)
# 
#     class Meta:
#         model = Question
#         fields = ['id', 'question_text', 'choices']
#         read_only_fields = ['id']
# 
#     def create(self, validated_data):
#         choices = validated_data.pop('choices')
#         question = Question.objects.create(**validated_data)
#         for choice in choices:
#             Choice.objects.create(question=question, **choice)
#         return question
# 
#     def update(self, instance, validated_data):
#         choices = validated_data['choices']
#         instance.question_text = validated_data['question_text']
#         instance.save()
#         # Only create new choices, dont update existing ones
#         for choice in choices:
#             try:
#                 choice_id = choice['choice_id']
#             except:
#                 Choice.objects.create(
#                     question = instance,
#                     choice_text = choice['choice_text']
#                 )
#         return instance
# 
# class VoteSerializer(serializers.ModelSerializer):
# 
#     class Meta:
#         model = Vote
#         fields = ['question', 'choice',]
# 
# Path: voting_app/polls/api/permissions.py
# class IsAuthenticatedCustom(BasePermission):
#     def has_permission(self, request, view):
#         if view.action == 'list' or view.action == 'retrieve':
#             return True
#         else:
#             if request.user.is_authenticated():
#                 return True
#             return False
# 
#     def has_object_permission(self, request, view, obj):
#         if request.method in permissions.SAFE_METHODS:
#             return True
#         return obj.author == request.user


from django.shortcuts import get_object_or_404
from django.db.models import Q
from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated , AllowAny
from rest_framework.decorators import detail_route, list_route
from ipware.ip import get_ip
from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter
from rest_auth.views import LoginView
from rest_auth.social_serializers import TwitterLoginSerializer
from ..models import Question, Choice, Vote
from .serializers import QuestionSerializer, \
VoteSerializer
from .permissions import IsAuthenticatedCustom
            return Response('You forgot to add choices')
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            new_question = serializer.save(author = request.user)
        return Response('New Question created')


    # Individual user polls/questions
    @list_route(methods=['get'], 
                permission_classes=[IsAuthenticatedCustom,])
    def mypolls(self, request):
        question = Question.objects.filter(author=self.request.user)
        question_serialized = QuestionSerializer(question, many=True)
        return Response(question_serialized.data)

    @detail_route(methods=['get', 'post'], 
                serializer_class=VoteSerializer,
                permission_classes=[AllowAny,])
    def vote(self, request, pk):
        """
        Vote for a given queastion
        """
        question = get_object_or_404(Question, id=pk)
        question_serialized = QuestionSerializer(question)
        if request.method == 'GET':
            data = {
                'question': question_serialized.data
            }
            return Response({'data': data})
        elif request.method == 'POST':

# Path: voting_app/polls/models.py
# class Question(models.Model):
#     author = models.ForeignKey(User, related_name='questions')
#     question_text = models.CharField(max_length=300)
#     created_date = models.DateTimeField(auto_now_add=True)
#     updated_date = models.DateTimeField(auto_now=True)
# 
#     class Meta:
#         ordering = ['-created_date']
# 
#     def __str__(self):
#         return self.question_text 
# 
# class Choice(models.Model):
#     question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE)
#     choice_text = models.CharField(max_length=200)
#     vote = models.PositiveIntegerField(db_index=True, default=0)
# 
#     def __str__(self):
#         return self.choice_text
# 
# class Vote(models.Model):
#     question = models.ForeignKey(Question, related_name='votes', on_delete=models.CASCADE)
#     vote_author = models.ForeignKey(User, related_name='votes', blank=True, null=True)
#     voter_ip = models.GenericIPAddressField(blank=True, null=True, db_index=True)
#     choice = models.ForeignKey(Choice, related_name='votes')
#     created_date = models.DateTimeField(auto_now_add=True)
# 
#     class Meta:
#         index_together = [
#             ["question", "vote_author"],
#             ["question", "voter_ip"],
#         ]
# 
# Path: voting_app/polls/api/serializers.py
# class QuestionSerializer(serializers.ModelSerializer):
# 
#     choices = ChoicesSerializerWithVote(many=True)
# 
#     class Meta:
#         model = Question
#         fields = ['id', 'question_text', 'choices']
#         read_only_fields = ['id']
# 
#     def create(self, validated_data):
#         choices = validated_data.pop('choices')
#         question = Question.objects.create(**validated_data)
#         for choice in choices:
#             Choice.objects.create(question=question, **choice)
#         return question
# 
#     def update(self, instance, validated_data):
#         choices = validated_data['choices']
#         instance.question_text = validated_data['question_text']
#         instance.save()
#         # Only create new choices, dont update existing ones
#         for choice in choices:
#             try:
#                 choice_id = choice['choice_id']
#             except:
#                 Choice.objects.create(
#                     question = instance,
#                     choice_text = choice['choice_text']
#                 )
#         return instance
# 
# class VoteSerializer(serializers.ModelSerializer):
# 
#     class Meta:
#         model = Vote
#         fields = ['question', 'choice',]
# 
# Path: voting_app/polls/api/permissions.py
# class IsAuthenticatedCustom(BasePermission):
#     def has_permission(self, request, view):
#         if view.action == 'list' or view.action == 'retrieve':
#             return True
#         else:
#             if request.user.is_authenticated():
#                 return True
#             return False
# 
#     def has_object_permission(self, request, view, obj):
#         if request.method in permissions.SAFE_METHODS:
#             return True
#         return obj.author == request.user


# Path: voting_app/polls/api/views.py
from django.shortcuts import get_object_or_404
from django.db.models import Q
from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated , AllowAny
from rest_framework.decorators import detail_route, list_route
from ipware.ip import get_ip
from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter
from rest_auth.views import LoginView
from rest_auth.social_serializers import TwitterLoginSerializer
from ..models import Question, Choice, Vote
from .serializers import QuestionSerializer, \
VoteSerializer
from .permissions import IsAuthenticatedCustom

            return Response('You forgot to add choices')
        serializer = QuestionSerializer(data=request.data)
        if serializer.is_valid():
            new_question = serializer.save(author = request.user)
        return Response('New Question created')


    # Individual user polls/questions
    @list_route(methods=['get'], 
                permission_classes=[IsAuthenticatedCustom,])
    def mypolls(self, request):
        question = Question.objects.filter(author=self.request.user)
        question_serialized = QuestionSerializer(question, many=True)
        return Response(question_serialized.data)

    @detail_route(methods=['get', 'post'], 
                serializer_class=VoteSerializer,
                permission_classes=[AllowAny,])
    def vote(self, request, pk):
        """
        Vote for a given queastion
        """
        question = get_object_or_404(Question, id=pk)
        question_serialized = QuestionSerializer(question)
        if request.method == 'GET':
            data = {
                'question': question_serialized.data
            }
            return Response({'data': data})
        elif request.method == 'POST':

            vote_serialized = VoteSerializer(data=request.data)