from rest_framework import serializers

from django.utils.translation import gettext as _

from profiles.models.ProfileModel import ProfileModel
from .models import ChatChannelModel, ChatMessageModel


class ChatChannelSerializer(serializers.ModelSerializer):

    members_id = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        model = ChatChannelModel
        fields = ["members_id", "pk"]

    def validate_members_id(self, value):
        members_id: [int] = value
        if len(members_id) < 2:
            raise serializers.ValidationError(_('There is not enough members to create the channel.'))
        if len(set(members_id)) != len(members_id):
            raise serializers.ValidationError(_('Duplicate in members list.'))
        for member_id in members_id:
            if not ProfileModel.objects.filter(pk=member_id).exists():
                raise serializers.ValidationError(_(f"The profile {member_id} doesn't exist."))
        return members_id


class ChatMessageSerializer(serializers.Serializer):

    class Meta:
        model = ChatMessageModel
        fields = ["channel_id", "author_id", "content", "time"]
