from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from .serializers import SimpleUserSerializer


User = get_user_model()


class UserLogin(ObtainJSONWebToken):
    permission_classes = [AllowAny]
    parser_classes = [JSONParser]

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            return Response(data={'token': serializer.object['token']},
                            status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UsersList(APIView):
    permission_classes = [IsAuthenticated]
    parser_classes = [JSONParser]

    @staticmethod
    def get(request):
        users = User.objects.all()
        if not users:
            return Response(data=[], status=status.HTTP_200_OK)
        serializer = SimpleUserSerializer(users, many=True)
        return Response(data=serializer.data, status=status.HTTP_200_OK)
