from rest_framework import serializers

from .base import DynamicFieldsSerializer
from .name import NameSerializer


class PersonSerializer(DynamicFieldsSerializer):
    domain_object_class = 'Person'

    id = serializers.IntegerField(required=False)
    login = serializers.CharField(required=False)
    name = NameSerializer(required=False)
    uid = serializers.CharField(required=False)
    is_dismissed = serializers.BooleanField(required=False)

    def restore_object(self, attrs, instance=None):
        login = attrs.get('login')
        if login and not instance:
            return (
                self.get_domain_object_class()
                    .objects(self.user, self.role_registry).get(login=login)
            )
        return super(PersonSerializer, self).restore_object(attrs, instance)
