"""Common serializers for app comment."""
from rest_framework import serializers

from comment.models import Comment


class CommentBaseSerializer(serializers.ModelSerializer):
    """Comment serializer"""
    nickname = serializers.CharField(read_only=True,
                                      source='user.username')
    is_mine = serializers.BooleanField(read_only=True)
    profile_pic = serializers.URLField(read_only=True,
                                       source='user.cropped_image_url')
    status_display = serializers.CharField(read_only=True,
                                           source='get_status_display')
    last_ip = serializers.IPAddressField(read_only=True, source='user.last_ip')

    content_type = serializers.SerializerMethodField(read_only=True)
    content_name = serializers.CharField(read_only=True, source='content_object.name')

    user_email = serializers.CharField(read_only=True, source='user.email')

    slug = serializers.CharField(read_only=True, source='content_object.slug')

    class Meta:
        """Serializer for model Comment"""
        model = Comment
        fields = [
            'id',
            'user_id',
            'is_mine',
            'created',
            'text',
            'mark',
            'nickname',
            'user_email',
            'profile_pic',
            'status',
            'status_display',
            'last_ip',
            'content_type',
            'content_name',
            'slug',
        ]
        extra_kwargs = {
            # 'status': {'read_only': True},
        }

    def get_content_type(self, instance: Comment):
        import establishment.serializers.common as establishment_serializers
        from establishment.models import EstablishmentType, Establishment
        from product.models import Product
        from product.serializers import ProductTypeBaseSerializer

        if isinstance(instance.content_object, Establishment):
            if instance.content_object.establishment_type == EstablishmentType.PRODUCER:
                return establishment_serializers.EstablishmentSubTypeBaseSerializer(
                    instance.content_object.establishment_subtypes, many=True
                ).data

            return establishment_serializers.EstablishmentTypeBaseSerializer(
                instance.content_object.establishment_type
            ).data
        if isinstance(instance.content_object, Product):
            return ProductTypeBaseSerializer(
                instance.content_object.product_type
            ).data
