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

from rest_framework import serializers

from mtp.apps.accounts.api.serializers import TrainerSerializer
from mtp.apps.accounts.apiv2.serializers import MTPUserSerializer

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)
    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',
        )
        read_only = ('id', 'trainer', 'state', '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', 'state',)


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.apiv2.serializer.MTPUserSerializer``
        The serialized trainee

    """

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