from rest_framework import serializers
from .models import User
from django.contrib import auth
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.tokens import RefreshToken, TokenError


class RegisterSerializer(serializers.ModelSerializer):
    password= serializers.CharField(max_length=68, min_length=6,
    write_only=True)

    class Meta:
        model = User
        fields = ['email','username','password','phone']
    
    def validate(self, attrs):
        email = attrs.get('email','')
        username = attrs.get('username','')
        username = attrs.get('phone','')
        if not username.isalnum():
            raise serializers.ValidationError('The username should only container alphanumeric')
        return attrs
    def create(self, validated_data):
        return User.objects.create_user(**validated_data)        

class EmailVerificationSerializer(serializers.ModelSerializer):
    token = serializers.CharField(max_length=555)

    class Meta:
        model = User
        fields = ['token']

class LoginSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(max_length=255, min_length=3)
    password = serializers.CharField(max_length=68,min_length=6,write_only=True)
    username = serializers.CharField(max_length=255, min_length=3, read_only=True)
    # tokens = serializers.SerializerMethodField()
    tokens = serializers.CharField(max_length=65, min_length=6, read_only=True)

    def get_tokens(self, obj):
        user = User.objects.get(email=obj['email'])
        return{
            'refresh': user.token()['reresh'],
            'access': user.tokens()['access']
        }
    class Meta:
        model = User
        fields = ['email','password','username','tokens']

    def validate(self,attrs):
        email = attrs.get('email','')
        password = attrs.get('password','')
        filtered_user_by_email = User.objects.filter(email=email)
        user = auth.authenticate(email=email, password=password)
        # if filter_user_by_email.exists() and filtered_user_by_email[0].auth_provider != 'email':
        #     raise AuthenticationFailed(
        #     detail = 'Please Continue your login using' + filtered_user_by_email[0].auth_provider
        # )
        if not user:
            raise AuthenticationFailed('Invalid Credenitials, try again')
        if not user.is_active:
            raise AuthenticationFailed('Account disabled, contact admin')
        if not user.is_verified:
            raise AuthentictionFailed('Email is not verified')

        return {
            'email': user.email,
            'username': user.username,
            'tokens': user.tokens
        }
        return super().validate(attrs)

    