import re
from django import forms
from django.core.validators import validate_email

from staff.person.models import Staff


def make_message(msg, logins):
    if logins:
        logins_str = ', '.join(logins)
        return msg.format(logins=logins_str)
    else:
        return ''


class SpamSendForm(forms.Form):
    logins = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'input-block-level'}),
        label='Список логинов')
    text = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'input-block-level'}),
        label='Шаблон письма')
    author = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'input-block-level'}),
        label='Кто спамер')
    is_html = forms.BooleanField(
        required=False,
        label='это ХТМЛ')

    def clean_author(self):
        author = self.cleaned_data['author'].strip()
        match = re.match(r'[^\<\>]+<([^\<\>]+)>', author)
        email = match.groups()[0] if match else author
        validate_email(email)
        return author

    def clean_logins(self):
        logins = self.cleaned_data['logins']
        logins = set(
            re.sub(r'[\s,;\'\"]+', ' ', logins).lower().strip().split()
        )

        persons = (
            Staff.objects
            .select_related('department')
            .filter(login__in=logins)
        )

        persons = {p.login: p for p in persons}
        found_logins = set(persons)

        not_found_logins = logins - found_logins

        dismissed_logins = [
            persons.pop(l).login
            for l in found_logins
            if persons[l].is_dismissed
        ]

        logins_wo_email = [
            persons.pop(l).login
            for l in persons.keys()
            if not persons[l].work_email.strip()
        ]

        self.data['logins'] = ', '.join(persons)

        errors = [
            'Максимальное количество логинов 500 переданно {0}'.format(
                len(logins)
            ) if len(logins) > 500 else '',
            make_message(
                'Следующие логины не были найдены: {logins}', not_found_logins
            ),
            make_message(
                'Следующие логины уволены: {logins}', dismissed_logins
            ),
            make_message(
                'Следующие логины не имеют адресов: {logins}', logins_wo_email
            ),
        ]
        errors = [e for e in errors if e]
        if errors:
            raise forms.ValidationError(errors)

        return list(persons.values())

    def clean_text(self):
        text = self.cleaned_data['text'].replace('\r', '')

        if '\n\n' not in text:
            raise forms.ValidationError('Subject от Body отделяется \\n\\n ')

        return text
