"""This module holds the serializers for the ``accounts`` app"""

from django.contrib.auth import get_user_model

from rest_framework import serializers

from ..models import Avatar, MTPUser


class AvatarSerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.accounts.models.Avatar`` model"""

    class Meta:
        model = Avatar
        fields = ('id', 'img', 'hash')


class UserSerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.accounts.models.MTPUser`` model"""

    photos = AvatarSerializer(many=True, read_only=True)
    groups = serializers.SlugRelatedField(
        source='mgroups', many=True, read_only=True, slug_field='name'
    )

    class Meta:
        model = MTPUser
        fields = (
            'id', 'username', 'first_name', 'last_name', 'email',
            'natural_language', 'photo', 'photos', 'groups',
        )
        read_only_fields = ('groups',)


class TrainerSerializer(UserSerializer):
    """Serializer for a ``mtp.apps.accounts.models.MTPUser``"""

    photo = serializers.SerializerMethodField()

    class Meta:
        model = get_user_model()
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 'photo')

    def get_photo(self, instance):
        """Get the photo url if any

        For the parameters, see ``rest_framework.serializers.ModelSerializer``

        Return
        ------
        str or None
            The photo url if any, else empty string.

        """

        return instance.photo.img.url if instance.photo else ''
