from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from rest_framework.authentication import SessionAuthentication

from django.utils.translation import gettext as _
from django.db.models import Q
from django.shortcuts import get_object_or_404

from ..models.FriendModel import FriendModel
from ..models.ProfileModel import ProfileModel
from ..serializers.ProfileSerializer import ProfileSerializer


class GetFriendsView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)

    def get(self, request):
        query = ProfileModel.objects.filter(user=request.user)
        if not query.exists():
            return Response(status=status.HTTP_400_BAD_REQUEST)
        friends = query[0].get_friends()
        return Response(ProfileSerializer(friends, many=True).data)


class EditFriendView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)

    def get_object(self):
        return ProfileModel.objects.get(pk=self.request.user.pk)

    def post(self, request, pk=None):
        user_profile = self.get_object()
        friend_profile = get_object_or_404(ProfileModel, pk=pk)

        if user_profile.pk == pk:
            return Response(_('You can\'t be friend with yourself.'), status.HTTP_400_BAD_REQUEST)

        if user_profile.is_friend(friend_profile):
            return Response(_('You are already friend with this user.'), status.HTTP_400_BAD_REQUEST)

        FriendModel(friend1=user_profile, friend2=friend_profile).save()
        return Response(_('Friendship succssfully created.'), status.HTTP_201_CREATED)

    def delete(self, request, pk=None):
        user_profile = self.get_object()
        friend_profile = get_object_or_404(ProfileModel, pk=pk)

        if not user_profile.is_friend(friend_profile):
            return Response(_('You are not friend with this user.'), status.HTTP_400_BAD_REQUEST)

        user_profile.delete_friend(friend_profile)
        return Response(_('Friendship succssfully deleted.'))
