<commit_before>from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from rest_framework.fields import DateTimeField

from foodsaving.conversations.models import Conversation, ConversationMessage, \
    ConversationParticipant, ConversationMessageReaction
from foodsaving.conversations.helpers import normalize_emoji_name


class ConversationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Conversation
        fields = [
            'id',
            'participants',
            'created_at',
            'updated_at',
            'seen_up_to',
            'unread_message_count',
            'email_notifications'
        ]

    seen_up_to = serializers.SerializerMethodField()
    unread_message_count = serializers.SerializerMethodField()
    updated_at = serializers.SerializerMethodField()
    email_notifications = serializers.SerializerMethodField()

    def get_seen_up_to(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        if not participant.seen_up_to:
            return None
        return participant.seen_up_to.id

    def get_unread_message_count(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        messages = conversation.messages
        if participant.seen_up_to:
            messages = messages.filter(id__gt=participant.seen_up_to.id)
        return messages.count()

    def get_updated_at(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        if participant.updated_at > conversation.updated_at:
            date = participant.updated_at
        else:
            date = conversation.updated_at
        return DateTimeField().to_representation(date)

    def get_email_notifications(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        return participant.email_notifications


class ConversationMarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationParticipant
        fields = ('seen_up_to',)

    def validate_seen_up_to(self, message):
        if not self.instance.conversation.messages.filter(id=message.id).exists():
            raise serializers.ValidationError('Must refer to a message in the conversation')
        return message

    def update(self, participant, validated_data):
        participant.seen_up_to = validated_data['seen_up_to']
        participant.save()
        return participant


class ConversationEmailNotificationsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationParticipant
        fields = ('email_notifications',)


class EmojiField(serializers.Field):
    """Emoji field is normalized and validated here"""

    def to_representation(self, obj):
        return obj

    def to_internal_value(self, data):
        try:
            return normalize_emoji_name(data)
        except Exception:
            raise serializers.ValidationError('not a valid emoji name')


class ConversationMessageReactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationMessageReaction
        fields = ('user', 'name', 'message')

    name = EmojiField()


class ConversationMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationMessage
        fields = [
            'id',<commit_msg>remove unneeded message field from reactions serializer<commit_after>from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from rest_framework.fields import DateTimeField

from foodsaving.conversations.models import Conversation, ConversationMessage, \
    ConversationParticipant, ConversationMessageReaction
from foodsaving.conversations.helpers import normalize_emoji_name


class ConversationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Conversation
        fields = [
            'id',
            'participants',
            'created_at',
            'updated_at',
            'seen_up_to',
            'unread_message_count',
            'email_notifications'
        ]

    seen_up_to = serializers.SerializerMethodField()
    unread_message_count = serializers.SerializerMethodField()
    updated_at = serializers.SerializerMethodField()
    email_notifications = serializers.SerializerMethodField()

    def get_seen_up_to(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        if not participant.seen_up_to:
            return None
        return participant.seen_up_to.id

    def get_unread_message_count(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        messages = conversation.messages
        if participant.seen_up_to:
            messages = messages.filter(id__gt=participant.seen_up_to.id)
        return messages.count()

    def get_updated_at(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        if participant.updated_at > conversation.updated_at:
            date = participant.updated_at
        else:
            date = conversation.updated_at
        return DateTimeField().to_representation(date)

    def get_email_notifications(self, conversation):
        user = self.context['request'].user
        participant = conversation.conversationparticipant_set.get(user=user)
        return participant.email_notifications


class ConversationMarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationParticipant
        fields = ('seen_up_to',)

    def validate_seen_up_to(self, message):
        if not self.instance.conversation.messages.filter(id=message.id).exists():
            raise serializers.ValidationError('Must refer to a message in the conversation')
        return message

    def update(self, participant, validated_data):
        participant.seen_up_to = validated_data['seen_up_to']
        participant.save()
        return participant


class ConversationEmailNotificationsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationParticipant
        fields = ('email_notifications',)


class EmojiField(serializers.Field):
    """Emoji field is normalized and validated here"""

    def to_representation(self, obj):
        return obj

    def to_internal_value(self, data):
        try:
            return normalize_emoji_name(data)
        except Exception:
            raise serializers.ValidationError('not a valid emoji name')


class ConversationMessageReactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationMessageReaction
        fields = ('user', 'name', 'message')
        extra_kwargs = {
            'message': {'write_only': True}
        }

    name = EmojiField()


class ConversationMessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConversationMessage
        fields = [
            'id',
{'fraction_non_alphanumeric': 0.07581227436823104, 'fraction_numerical': 0.0, 'mean_word_length': 3.25, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '961667', 'n_tokens_mistral': 1926, 'n_tokens_neox': 1880, 'n_words': 399}