from rest_framework.serializers import ModelSerializer, CharField, ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth import get_user_model
from .models import User as mobile, OTPCode, Session, MessageSMS, ChatRoom, MessageChat, Payment

# from django.contrib.auth import get_user_model

UserGet = get_user_model()

class DefaultUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class MobileSerializer(ModelSerializer):
    class Meta:
        model = mobile
        fields = '__all__'
        depth = 1

class OTPCodeSerializer(ModelSerializer):
    class Meta:
        model = OTPCode
        fields = '__all__'
        read_only_fields = ('code', )


class SessionSerializer(ModelSerializer):
    class Meta:
        model = Session
        fields = '__all__'


class MessageSerializer(ModelSerializer):
    class Meta:
        model = MessageSMS
        fields = '__all__'


class ChatRoomSerializer(ModelSerializer):
    user_1, user_2 = DefaultUserSerializer(read_only=True), DefaultUserSerializer(read_only=True)
    class Meta:
        model = ChatRoom
        fields = '__all__'
        depth = 1


class MessageChatSerializer(ModelSerializer):
    sender = DefaultUserSerializer(read_only=True)
    
    class Meta:
        model = MessageChat
        fields = '__all__'
        depth = 1


class PaymentSerializer(MobileSerializer):
    class Meta:
        model = Payment
        fields = '__all__'


# Authentication method : Passwd
class RegisterSerializer(ModelSerializer):
    password = CharField(write_only=True, required=True, validators=[validate_password])
    password2 = CharField(write_only=True, required=True)

    class Meta:
        model = UserGet
        fields = ('username', 'password', 'password2', 'email')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise ValidationError({"password": "رمز عبور و تکرار آن برابر نیستند."})
        return attrs

    def create(self, validated_data):
        user = UserGet.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
        )
        user.set_password(validated_data['password'])
        user.save()
        return user