# coding: utf-8

from django.utils.translation import gettext as _

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


class List(serializers.ModelSerializer):

    author = UserBrief()
    invitees = PKPrettyField(
        serializer=UserBrief, required=False, many=True, read_only=True
    )
    attachments = AttachmentField(many=True, required=False)
    can_edit = serializers.BooleanField()

    class Meta:
        model = models.EnquiryComment
        fields = (
            'id',
            'enquiry',
            'created_at',
            'updated_at',
            'author',
            'message',
            'message_html',
            'is_from_email',
            'attachments',
            'can_edit',
            'invitees',
        )


class RetrieveUpdate(serializers.ModelSerializer):

    author = UserBrief(read_only=True)
    attachments = AttachmentField(many=True, required=False)
    invitees = PKPrettyField(
        serializer=UserBrief, required=False, many=True, read_only=True
    )

    class Meta:
        model = models.EnquiryComment
        fields = (
            'id',
            'message',
            'author',
            'updated_at',
            'attachments',
            'invitees',
        )
        extra_kwargs = {'message': {'style': {'x-wf': True}, 'label': ' '}}

    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.enquiry_comment is None
            or att.enquiry_comment_id == instance.pk
        ]
        return super().update(instance, data)


class Create(serializers.ModelSerializer):

    attachments = AttachmentField(required=False, many=True)
    message = serializers.CharField(
        allow_blank=True, style={'x-wf': True}, label=' '
    )
    invitees = EmployeeField(
        required=True,
        many=True,
        label=' ',
        style={'x-hint': _('MODEL_ENQUIRY_COMMENT::INVITEES')},
    )
    author = UserBrief(read_only=True)

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


class Log(serializers.ModelSerializer):

    attachments = AttachmentField(many=True)
    invitees = PKPrettyField(
        serializer=UserBrief, required=False, many=True, read_only=True
    )
    author = UserBrief()

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