"""This module holds the serializers of the ``trainings`` app"""

from rest_framework import serializers

from mtp.apps.accounts.api.serializers import TrainerSerializer, UserSerializer

from ..models import Training, TrainingSession


class TrainingSerializer(serializers.ModelSerializer):
    """Serializer for the ``Training`` model"""

    tags = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()

    class Meta:
        model = Training
        fields = ('id', 'name', 'description', 'image', 'tags')

    def get_image(self, obj):
        if obj.thumbnail_image:
            return obj.thumbnail_image.url
        else:
            return ''

    def get_tags(self, obj):
        return [ obj.VERSION_STATES.for_value(obj.version_state).display ]


class TrainingSessionReadSerializer(serializers.ModelSerializer):
    """The serializer for the list of ``TrainingSession`` model

    Notes
    -----
    All attributes are inherited from the models, excepting:
    - ``is_live`` who is computed on the fly by a method below.
    - ``is_attendee`` who is coming from the querySet of the view.

    See also
    --------
    ``mtp.apps.api.views.SessionList``

    """
    training = TrainingSerializer(many=False, read_only=False)
    trainer = TrainerSerializer(many=False, read_only=True)
    is_live = serializers.SerializerMethodField()
    is_attendee = serializers.NullBooleanField(default=False, required=False)
    date = serializers.DateTimeField(source='start_date')
    date_end = serializers.DateTimeField(source='end_date')

    class Meta:
        model = TrainingSession
        fields = (
            'id', 'date', 'date_end', 'state',
            'permissions', 'training', 'trainer', 'users', 'is_live', 'is_attendee'
        )
        read_only = ('id', 'trainer', 'is_live', 'is_attendee')

    def get_is_live(self, obj):
        return obj.is_live()


class TrainingSessionWriteSerializer(serializers.ModelSerializer):

    date = serializers.DateTimeField(source="start_date")
    date_end = serializers.DateTimeField(source="end_date")

    class Meta:
        model = TrainingSession
        fields = (
            'id', 'date', 'date_end', 'state',
            'permissions', 'training',  'users'
        )
        read_only = ('id')


class SessionChallengeScoreSerializer(serializers.Serializer):
    """Serializer for the session trainee's score

    Attributes
    ----------
    score : ``rest_framework.serializers.IntegerField``
        The serialized score of the trainee
    trainee : ``mtp.apps.api.serializer.UserSerializer``
        The serialized trainee

    """

    score = serializers.IntegerField()
    trainee = UserSerializer()
