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 rest_framework.request import Request

from django.contrib.auth.models import User
from django.utils.translation import gettext as _

from ..models.BlockModel import BlockModel
from ..models.ProfileModel import ProfileModel
from ..serializers.ProfileSerializer import ProfileSerializer


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

    def get(self, request: Request):
        profiles = []
        blocks = BlockModel.objects.filter(blocker=request.user)
        for block in blocks:
            profile = ProfileModel.objects.filter(user=block.blocked)
            if (profile.exists()):
                profiles.append(profile[0])

        return Response(ProfileSerializer(profiles, many=True).data)


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

    def post(self, request, pk=None):
        if (pk == request.user.pk):
            return Response(_('You can\'t block yourself.'), status.HTTP_400_BAD_REQUEST)

        blocked = User.objects.filter(pk=pk)
        if (not blocked.exists()):
            return Response(_('This user doesn\'t exist.'), status.HTTP_404_NOT_FOUND)

        if (BlockModel.objects.filter(blocker=request.user, blocked=pk)):
            return Response(_('You already blocked this user.'), status=status.HTTP_409_CONFLICT)

        BlockModel(blocker=request.user, blocked=blocked[0]).save()

        return Response(status=status.HTTP_201_CREATED)

    def delete(self, request, pk=None):
        if (pk == request.user.pk):
            return Response(_('You can\'t unblock yourself.'), status.HTTP_400_BAD_REQUEST)

        blocked = User.objects.filter(pk=pk)
        if (not blocked.exists()):
            return Response(_('This user doesn\'t exist.'), status.HTTP_404_NOT_FOUND)

        block = BlockModel.objects.filter(blocker=request.user, blocked=blocked[0])
        if (not block):
            return Response(_('This user isn\'t blocked.'), status.HTTP_400_NOT_FOUND)

        block.delete()
        return Response(status=status.HTTP_200_OK)
