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

from rest_framework import serializers

from mtp.apps.accounts.models import MTPUser
from mtp.apps.accounts.apiv2.serializers import MTPUserSerializer

from ..models import Training, TrainingSession


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

    business_unit = serializers.SerializerMethodField()
    job_profile = serializers.SerializerMethodField()
    original_id = serializers.PrimaryKeyRelatedField(source='original_version', read_only=True)
    tags = serializers.SerializerMethodField()

    class Meta:
        model = Training
        fields = (
            'business_unit',
            'description',
            'external_id',
            'id',
            'is_assessing',
            'job_profile',
            'name',
            'original_id',
            'tags',
            'thumbnail_image',
        )

    def get_business_unit(self, obj):
        """Return the name of the business unit

        Returns
        -------
        str or None
            The name of the business unit, or None if no business unit

        """

        return obj.business_unit.name if obj.business_unit else None

    def get_job_profile(self, obj):
        """Return the name of the job profile

        Returns
        -------
        str or None
            The name of the job profile, or None if no job profile

        """

        return obj.job_profile.name if obj.job_profile else None

    @staticmethod
    def get_tags(instance):
        """Get training tags.

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

        return [instance.get_version_state_display()]


class TrainingSessionSerializer(serializers.ModelSerializer):
    """Serializer for the ``TrainingSession`` model."""

    trainer = MTPUserSerializer(read_only=True)
    trainer_id = serializers.PrimaryKeyRelatedField(
        source='trainer',
        queryset=MTPUser.objects.non_deleted(),
        write_only=True,
        required=False,
    )
    training = TrainingSerializer(read_only=True)
    training_id = serializers.PrimaryKeyRelatedField(
        source='training',
        queryset=Training.objects.non_deleted(),
        write_only=True,
    )

    class Meta:
        model = TrainingSession
        fields = (
            'end_date',
            'id',
            'is_live',
            'permissions',
            'start_date',
            'state',
            'token',
            'trainer',
            'trainer_id',
            'training',
            'training_id',
            'users',
        )
        read_only_fields = (
            'token',
            'users',
            'state',
        )


class TokenSerializer(serializers.ModelSerializer):
    """Serializer for the token of ``TrainingSession`` model."""

    class Meta:
        model = TrainingSession
        fields = (
            'id',
        )
