from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from module_iam.models import AppVersion, IAmPrincipal
from module_project import constants

# class BasePasswordSerializer(serializers.Serializer):
#     confirm_password = serializers.CharField(write_only=True, required=True)

#     def validate(self, attrs):
#         password = attrs.get("password")
#         confirm_password = attrs.pop("confirm_password")
#         if password != confirm_password:
#             raise serializers.ValidationError({'password': constants.PASSWORD_NOT_MATCH})
#         return super().validate(attrs)

#     def update(self, instance, validate_data):
#         new_password = validate_data.get("password")
#         if new_password:
#             instance.password = make_password(new_password)
#         instance.save()
#         return instance

class RegistrationSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=IAmPrincipal.objects.all(), message="This email address is already in use.")]
    )
    password = serializers.CharField(write_only=True, required=True)
    confirm_password = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = IAmPrincipal
        fields = [
            "first_name",
            "email",
            "phone_no",
            "password",
            "confirm_password",
            "player_id",
        ]

    def validate(self, attrs):
        email = attrs.get("email")
        phone_no = attrs.get("phone_no")
        password = attrs.get("password")
        confirm_password = attrs.get("confirm_password")

        if password != confirm_password:
            raise serializers.ValidationError({'password': constants.PASSWORD_NOT_MATCH})

        obj = self.Meta.model.objects.filter(email=email).first()

        if obj:
            raise serializers.ValidationError({"email": constants.EMAIL_EXISTS})

        return attrs

    def create(self, validated_data):
        del validated_data['confirm_password']
        validated_data["username"] = validated_data["email"]
        validated_data["password"] = make_password(validated_data["password"])
        principal = self.Meta.model.objects.create(**validated_data)
        return principal

    def update(self, instance, validated_data):
        # update prinicpal instance fiedls based on the validation data
        instance.first_name = validated_data.get("first_name", instance.first_name)
        instance.email = validated_data.get("email", instance.email)
        instance.username = validated_data.get("email", instance.email)
        instance.save()
        return instance


class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(write_only=True, required=True)
    password = serializers.CharField(write_only=True, required=True)
    player_id = serializers.CharField(write_only=True, required=True)

class OtpVerificationSerializer(serializers.Serializer):
    email = serializers.EmailField(write_only=True, required=True)
    otp = serializers.IntegerField(write_only=True, required=True)

class PasswordResetSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True)
    confirm_password = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = IAmPrincipal
        fields = [
            "password",
            "confirm_password"
        ]

    def validate(self, attrs):
        password = attrs.get("password")
        confirm_password = attrs.get("confirm_password")
        if password != confirm_password:
            raise serializers.ValidationError({'password': constants.PASSWORD_NOT_MATCH})
        return super().validate(attrs)

    def update(self, instance, validate_data):
        new_password = validate_data.get("password")
        if new_password:
            instance.password = make_password(new_password)
        instance.save()
        return instance

class AppVersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = AppVersion
        fields = [
            "device_type",
            "version",
            "force_upgrade",
            "recommend_upgrade",
        ]