"""This module contains the v2 api related-serializers for the accounts app"""

from django.conf import settings
from django.contrib.auth import get_user_model

from rest_framework import serializers

from ..constants import (
    INTERNAL_GROUP_TRAINEE,
    INTERNAL_GROUP_WHOSWHO
)
from ..models import (
    Group,
    GroupRole,
    MTPUser,
)


class MTPUserSerializer(serializers.ModelSerializer):
    """Serializer for the ``MTPUser`` model"""

    password = serializers.CharField(write_only=True)
    language = serializers.CharField(source='natural_language')
    profile_picture = serializers.SerializerMethodField()
    groups = serializers.SlugRelatedField(
        source='mgroups', many=True, read_only=True, slug_field='name'
    )

    class Meta:
        model = get_user_model()
        fields = (
            'id',
            'username',
            'first_name',
            'last_name',
            'email',
            'language',
            'profile_picture',
            'groups',
            'password',
            'external_id',
        )

    def create(self, validated_data):
        """Create a new ``MTPUser``

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

        Notes
        -----
        Only the trainees can register themselves through the API at the moment.
        The username is transformed to lowercase.

        """

        user = get_user_model().objects.create(
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
            email=validated_data['email'],
            natural_language=validated_data['natural_language'],
            username=validated_data['username'].lower()
        )
        user.set_password(validated_data['password'])

        if settings.INSTANCE_IS_SLAVE:
            user.created_from = MTPUser.ORIGINS.SLAVE_REGISTRATION
        else:
            user.created_from = MTPUser.ORIGINS.MASTER_REGISTRATION

        user.save()

        # We register the user into the proper groups
        GroupRole.objects.create(
            user=user,
            group=Group.objects.get(name=INTERNAL_GROUP_TRAINEE)
        )
        GroupRole.objects.create(
            user=user,
            group=Group.objects.get(name=INTERNAL_GROUP_WHOSWHO)
        )

        return user

    @staticmethod
    def get_profile_picture(instance):
        """Get the profile picture url for this user

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

        Returns
        -------
        str or None
            The url of the profile picture, or None if the user doesn't have a profile picture

        """

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