"""
This module contains the signal handlers of the :py:mod:`managemails` app.

The module starts Celery_ tasks.

.. _Celery: https://www.celeryproject.org/

"""
import logging

from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver

from fileservertasks.tasks import create_file_mailbox, delete_file_mailbox
from managemails.models import Mailbox
from taskresults.models import TaskResult

_LOGGER = logging.getLogger(__name__)


@receiver(post_save, sender=Mailbox)
def handle_mailbox_created(sender, instance, created, **kwargs):
    """
    Handles post creation actions on :py:class:`Mailbox <managemails.models.Mailbox>` instances.

    :param sender: sender of the signal
    :param instance: Mailbox instance
    :param created: whether the instance has just been created

    This signal handler starts a Celery_ task.

    """
    if created:
        task_result = TaskResult.objects.create_task_result(
            "handle_mailbox_created",
            create_file_mailbox.s(instance.osuser.username, instance.username),
        )
        _LOGGER.info(
            "Mailbox creation has been requested in task %s", task_result.task_id
        )
    _LOGGER.debug(
        "mailbox %s has been %s", instance, created and "created" or "updated"
    )


@receiver(post_delete, sender=Mailbox)
def handle_mailbox_deleted(sender, instance, **kwargs):
    """
    Handles cleanup actions to be done after deletion of a
    :py:class:`Mailbox <managemails.models.Mailbox>` instance.

    :param sender: sender of the signal
    :param instance: Mailbox instance

    This signal handler starts a Celery_ task.

    """
    task_result = TaskResult.objects.create_task_result(
        "handle_mailbox_deleted",
        delete_file_mailbox.s(instance.osuser.username, instance.username),
    )
    _LOGGER.info("Mailbox deletion has been requested in task %s", task_result.task_id)
