from django.shortcuts import render
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from .models import CustomUser
from .serializers import UserSerializerWithToken
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
# Create your views here.
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        # attrs['email'] = attrs['email'].lower()
        data = super().validate(attrs)
        serializer = UserSerializerWithToken(self.user).data
        for k, v in serializer.items():
            data[k] = v
        return data

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer


@api_view(['POST'])
def register_user(request):
    data = request.data
    print(data)
    try:
        user = CustomUser.objects.create(
            name=data['name'],
            date_of_birth =data['date_of_birth'],
            email=data['email'].lower(),
            password=make_password(data['password'])
        )
        
        serializer = UserSerializerWithToken(user, many=False)
        print(serializer.data)
        return Response(serializer.data)
    except:
        print("hello")
        message = {'detail': 'User with this email already exists'}
        return Response(message, status=400)