import re

from django import forms

from staff.departments.models import Department


VALID_LETTERS = 'a-zA-Zа-яА-ЯёЁҐґІіЇїЄєşŞıİçÇöÖüÜĞğÄäßĆćČčŁłŃńŚśŠšŹźŽžŬŭ'
VALID_LETTERS_EN = 'a-zA-Z'


class DepartmentIdValidator(object):

    def __call__(self, value):
        if value and not (
                Department.objects
                          .filter(id=value, intranet_status=1)
                          .exists()):
            raise forms.ValidationError(
                '{"error_key": "staff-invalid_department_id"}',
                code='staff_invalid_department_id')


department_id_validator = DepartmentIdValidator()


class LatinFieldValidator(object):
    regex = re.compile(r'^[\x20-\x7E\s]+$')  # like [[:print:]]

    def __call__(self, value):
        if value:
            value = value.strip()
        if value and not self.regex.match(value):
            raise forms.ValidationError(
                '{"error_key": "staff-invalid_latin_field"}',
                code='staff_invalid_latin_field')


latin_field_validator = LatinFieldValidator()


class EmptyFieldValidator(object):
    regex = re.compile(r'^[\s]*$')

    def __call__(self, value):
        if self.regex.match(value):
            raise forms.ValidationError(
                '{"error_key": "staff-empty_field"}',
                code='staff_empty_field')


empty_field_validator = EmptyFieldValidator()


class NameValidator(object):
    regex = re.compile(
        r'^[{letter_character}][{letter_character}\-\'’ () ́]+$'.format(
            letter_character=VALID_LETTERS,
        )
    )
    checkers = [
        lambda value: '  ' in value,
        lambda value: '--' in value,
        lambda value: '\'\'' in value,
    ]

    def __call__(self, value):
        if value:
            value = value.strip()

        if any((checker(value) for checker in self.checkers)) or not self.regex.match(value):
            raise forms.ValidationError(
                '{"error_key": "staff-invalid_name_field"}',
                code='staff_invalid_name_field'
            )


class NameEnValidator(NameValidator):
    regex = re.compile(
        r'^[{letter_character}][{letter_character}\-\'’ () ́]+$'.format(
            letter_character=VALID_LETTERS_EN
        )
    )


class MiddleNameValidator(NameValidator):
    regex = re.compile(
        r'^[{letter_character}][{letter_character}\-\'’ ́ ]+$'.format(
            letter_character=VALID_LETTERS
        )
    )


name_validator = NameValidator()
middle_name_validator = MiddleNameValidator()
name_en_validator = NameEnValidator()
