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 (
    UserModel as mobile,
    SessionModel as Session,
)

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 SessionSerializer(ModelSerializer):
    class Meta:
        model = Session
        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