from rest_framework import generics
from django.contrib.auth import authenticate, login, logout
from rest_framework.authentication import SessionAuthentication
import json
from django.views.decorators.http import require_POST
from django.http import JsonResponse
from django.middleware.csrf import get_token
from rest_framework.views import APIView
from rest_framework import status, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from User.serializers import UserSerializer, DetailedUserSerializer
from .models import BasicUser
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from django.forms.models import model_to_dict


def get_csrf(request):
    response = JsonResponse({"Info": "Success - Set CSRF cookie"})
    response["X-CSRFToken"] = get_token(request)
    return response


@require_POST
def loginView(request):
    data = json.loads(request.body)
    username = data.get("username")
    password = data.get("password")

    if username is None or password is None:
        return JsonResponse({"messsage": "Username and Password is needed"})

    user = authenticate(username=username, password=password)

    if user is None:
        return JsonResponse({"message": "User does not exist"}, status=400)

    login(request, user)
    return JsonResponse({"message": "User logged in successfully"})


class WhoAmIView(APIView):
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]

    @staticmethod
    def get(request, format=None):
        serializer = DetailedUserSerializer(request.user)
        return JsonResponse({"user": serializer.data})


@require_POST
def logout_view(request):
    logout(request)
    return JsonResponse({"messsage": "User logged out"})


@require_POST
def create_user_view(request):
    #Create a new user
    userData = {}
    data = json.loads(request.body)
    if "username" in data.keys():
        userData['username'] = data['username']
        data.pop('username', None)
    if "email" in data.keys():
        userData['email'] = data['email']
        data.pop('email', None)
    if "password" in data.keys():
        userData['password'] = data['password']
        data.pop('password', None)
    if "first_name" in data.keys():
        userData['first_name'] = data['first_name']
        data.pop('first_name', None)
    if "last_name" in data.keys():
        userData['last_name'] = data['last_name']
        data.pop('last_name', None)
    try:
        user = BasicUser.objects.create_user(**userData)
        for key in data:
            setattr(user, key, data[key])
        user.save()
    except Exception as e:
        return JsonResponse({"error": str(e)})

    return JsonResponse({"user": model_to_dict(user)}, status=500)


class UserListView(generics.ListAPIView):
    queryset = BasicUser.objects.all()
    serializer_class = UserSerializer


class UserCreateView(generics.CreateAPIView):
    serializer_class = UserSerializer


class UserView(generics.RetrieveAPIView):
    queryset = BasicUser.objects.all()
    serializer_class = DetailedUserSerializer

    # @permission_classes([IsAuthenticated])
    # class UserVIew(generics.ListAPIView):
    #     print(self.kwargs.get('username', None))

    # class CreateUserAPIView(CreateAPIView):
    #     serializer_class = CreateUserSerializer
    #     permission_classes = [AllowAny]

    #     def create(self, request, *args, **kwargs):
    #         serializer = self.get_serializer(data=request.data)
    #         serializer.is_valid(raise_exception=True)
    #         self.perform_create(serializer)
    #         headers = self.get_success_headers(serializer.data)
    #         # We create a token than will be used for future auth
    #         token = Token.objects.create(user=serializer.instance)
    #         token_data = {"token": token.key}
    #         return Response(
    #             {**serializer.data, **token_data},
    #             status=status.HTTP_201_CREATED,
    #             headers=headers
    #         )

    # class LogoutUserAPIView(APIView):
    #     queryset = get_user_model().objects.all()

    #     def get(self, request, format=None):
    #         # simply delete the token to force a login
    #         request.user.auth_token.delete()
    #         return Response(status=status.HTTP_200_OK)

    # class ViewBasicUserView(viewsets.ModelViewSet):

    #     serializer_class = ViewBasicUserSerializer
    #     permission_classes = [IsAuthenticated]

    #     def get_queryset(self):
    #         return get_user_model().objects.filter(pk=self.request.user.id)
