import sform

from intranet.femida.src.api.core.forms import (
    AttachmentMultipleSuggestField,
    ApplicationChoiceField,
    EMPTY_LABEL,
)
from intranet.femida.src.candidates.helpers import get_main_email
from intranet.femida.src.communications.choices import MESSAGE_TYPES
from intranet.femida.src.communications.validators import validate_future_time
from intranet.femida.src.interviews.models import Application


class ExternalMessageForm(sform.SForm):

    email = sform.EmailField(max_length=255, state=sform.REQUIRED)
    subject = sform.CharField(max_length=255, state=sform.REQUIRED)
    text = sform.CharField(state=sform.REQUIRED)
    attachments = AttachmentMultipleSuggestField()
    schedule_time = sform.DateTimeField(validators=[validate_future_time])

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.candidate = self.context.get('candidate')
        assert self.candidate is not None

        email = get_main_email(self.candidate)
        if email:
            self.fields['email'].default = email

    def clean(self):
        cleaned_data = super().clean()
        cleaned_data['candidate'] = self.candidate
        cleaned_data['type'] = MESSAGE_TYPES.outcoming
        return cleaned_data


class MessageUpdateForm(sform.SForm):
    """
    Used for internal communication and notes
    """
    text = sform.CharField(state=sform.REQUIRED)
    attachments = AttachmentMultipleSuggestField()


class ConsiderationMessageListFilterForm(sform.SForm):
    """
    Форма, по которой происходит фильтрация списка сообщений

    Используется для внутренней коммуникации.
    """
    application = ApplicationChoiceField(
        queryset=Application.unsafe.none(),
        empty_label=EMPTY_LABEL,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        consideration = self.context.get('consideration')
        assert consideration is not None
        self.fields['application'].queryset = (
            Application.objects
            .filter(consideration=consideration)
        )
