# coding: utf-8

from django.utils.translation import gettext_lazy as _

from procu.api import models
from procu.api.common.fields import AttachmentField
from procu.api.user.serializers import UserBrief
from procu.rest import serializers
from procu.rest.exceptions import ValidationError


class User(serializers.ModelSerializer):
    full_name = serializers.CharField()

    class Meta:
        model = models.User
        fields = ('id', 'full_name')


class Create(serializers.Serializer):
    message = serializers.CharField(required=True, allow_blank=True, label=' ')
    attachments = serializers.ListField(child=serializers.IntegerField())


class List(serializers.ModelSerializer):

    attachments = AttachmentField(many=True, required=False)
    can_edit = serializers.BooleanField()
    author = User()

    class Meta:
        model = models.QuoteComment

        fields = (
            'id',
            'quote',
            'updated_at',
            'author',
            'message',
            'message_html',
            'attachments',
            'is_suspicious',
            'is_from_email',
            'can_edit',
        )


class RetrieveUpdate(serializers.ModelSerializer):

    author = User(read_only=True)
    attachments = AttachmentField(many=True, required=False)

    def validate(self, data):

        if not data.get('message', True) and not data.get('attachments', True):
            raise ValidationError(
                {'message': _('COMMENTS::ERROR_BLANK_NO_FILES')}
            )

        return data

    def update(self, instance, data):
        data['attachments'] = [
            att
            for att in data.get('attachments', ())
            if att.comment_id is None or att.comment_id == instance.pk
        ]
        return super().update(instance, data)

    class Meta:
        model = models.QuoteComment
        fields = ('id', 'author', 'updated_at', 'message', 'attachments')
        extra_kwargs = {'message': {'label': ' '}}


class Log(serializers.ModelSerializer):

    attachments = AttachmentField(many=True)
    author = UserBrief()

    class Meta:
        model = models.QuoteComment
        fields = ('id', 'author', 'message', 'attachments')
