from rest_framework import serializers
from ces_fall_rest_api.models.user import User
# from ces_fall_rest_api.models.student_in_section import StudentInSection


class UserSerializer(serializers.ModelSerializer):
    """This class allow User model to convert to Python datatype 
    that can be rendered into JSON, XML, or other content types. 

    Args:
        serializers (_type_): serializers class

    """
    class Meta:
        model = User
        fields = ['username', 'pid', 'first_name',
                  'last_name', 'password', 'email']
        # extra_kwargs = {'username': {'write_only': True}}
    
    # method to create new user in the database.
    def create(self, validated_data):
        return User.objects.create(**validated_data)

    # method to make an update to an existing user in the database
    def update(self, instance, validated_data):
        instance.update_fields(validated_data)
        
        password = validated_data.get('password', instance.password)
        # if the password field is empty, use default password
        if not password:
            instance.set_default_password()
        elif password != instance.password:
            instance.set_password(password)
        instance.save()
        return instance
