"""This module holds the model serializers for the ``roleplays`` app"""

from rest_framework import serializers

from .models import Criterion, Rating, Roleplay, Step

class CriterionSerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.roleplays.models.Criterion`` model."""

    class Meta:
        model = Criterion
        fields = (
            'id',
            'name',
            'description',
            'criterion_type',
        )


class StepSerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.roleplays.models.Step`` model."""

    criteria = CriterionSerializer(many=True)
    duration = serializers.SerializerMethodField()

    class Meta:
        model = Step
        fields = (
            'id',
            'name',
            'description',
            'duration',
            'criteria',
        )

    def get_duration(self, obj):
        return obj.duration.total_seconds()


class RoleplaySerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.roleplays.models.Roleplay`` model."""

    steps = StepSerializer(many=True)

    class Meta:
        model = Roleplay
        fields = (
            'id',
            'name',
            'description',
            'are_criteria_ratings_editable',
            'criteria_rating_scale',
            'criteria_rating_type',
            'steps',
        )


class RatingListSerializer(serializers.ListSerializer):
    """ListSerializer for multiple ``mtp.apps.roleplays.models.Rating`` models."""


class RatingSerializer(serializers.ModelSerializer):
    """Serializer for the ``mtp.apps.roleplays.models.Rating`` model.

    Example
    -------

    For multiple new ``Rating`` instances.
    Given that we already have a ``training_session`` and a ``trainee``
    in the context.

    >>> ratings = [
    >>>     { # Criterion quantitative
    >>>         'criterion': criterion1_id,
    >>>         'score': 2
    >>>     },
    >>>     { # Criterion qualitative
    >>>         'criterion': criterion2_id,
    >>>         'score': 1
    >>>     }
    >>> ]
    >>>
    >>> serialized_ratings = RatingSerializer(data=ratings, many=True)
    >>>
    >>> ratings = serialized_ratings.save()

    See also
    --------

    ``mtp.apps.roleplays.managers.RatingManager.save_rating`` method.

    """

    def create(self, validated_data):
        rating = Rating(**validated_data)
        Rating.objects.save_rating(rating)

        return rating

    class Meta:
        model = Rating
        fields = (
            'criterion',
            'text',
            'score'
        )

