import logging
import yenv

from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.dispatch import receiver

from staff.dismissal.signals import dismissal_completed

from .controllers import EmailRedirectionController


logger = logging.getLogger(__name__)


def is_email_valid(email):
    if not email:
        return False

    try:
        validate_email(email)
        return True

    except ValidationError:
        return False


@receiver(dismissal_completed)
def handle_dismissal_completed(staff, **kw):
    """Сохраняет данные о перенаправлении почты"""

    dismissal = kw.get('dismissal')

    if dismissal:
        ctrl = EmailRedirectionController()
        ctrl.create_redirection(
            just_dismissed=staff,
            forward_correspondence_to=dismissal.forward_correspondence_to,
        )


def delete_email_redirections(staff):
    """Отменяет перенаправление почты восстановленного сотрудника"""
    ctrl = EmailRedirectionController()
    ctrl.notify_restored(staff)


def update_staff_emails(staff):
    from staff.emails.tasks import SyncStaffEmails

    if yenv.type != 'development':
        SyncStaffEmails.apply_async(kwargs={'staff_id': staff.instance.id}, countdown=40)
    else:
        SyncStaffEmails(staff_id=staff.instance.id)
