"""Django signal handlers for modoboa_postfix_autoreply."""

from django.db.models import signals
from django.dispatch import receiver

from modoboa.admin import models as admin_models

from . import models


@receiver(signals.post_save, sender=admin_models.Domain)
def manage_transport_entry(sender, instance, **kwargs):
    """Create or update a transport entry for this domain."""
    if kwargs.get("created"):
        models.Transport.objects.get_or_create(
            domain="autoreply.{}".format(instance), method="autoreply:"
        )
        return
    oldname = getattr(instance, "oldname", "None")
    if oldname is None or oldname == instance.name:
        return
    models.Transport.objects.filter(
        domain="autoreply.%s" % oldname).update(
            domain="autoreply.%s" % instance.name)
    qset = (
        admin_models.AliasRecipient.objects
        .select_related("alias", "r_mailbox")
        .filter(
            alias__domain=instance, alias__internal=True,
            address__contains="@autoreply")
    )
    for alr in qset:
        alr.address = alr.address.replace(oldname, instance.name)
        alr.save()


@receiver(signals.post_delete, sender=admin_models.Domain)
def delete_transport_entry(sender, instance, **kwargs):
    """Delete a transport entry."""
    models.Transport.objects.filter(
        domain="autoreply.{}".format(instance)).delete()


@receiver(signals.post_save, sender=admin_models.Mailbox)
def manage_autoreply_alias(sender, instance, **kwargs):
    """Create an alias for routing."""
    if kwargs.get("created"):
        alias, created = admin_models.Alias.objects.get_or_create(
            address=instance.full_address, domain=instance.domain,
            internal=True)
        admin_models.AliasRecipient.objects.create(
            alias=alias,
            address="{}@autoreply.{}".format(
                instance.full_address, instance.domain))
        return
    old_address = getattr(instance, "old_full_address", None)
    if old_address is None or old_address == instance.full_address:
        return
    admin_models.AliasRecipient.objects.filter(
        address__contains="{}@autoreply".format(old_address)).update(
            address="{}@autoreply.{}".format(
                instance.full_address, instance.domain))


@receiver(signals.post_delete, sender=admin_models.Mailbox)
def delete_autoreply_alias(sender, instance, **kwargs):
    """Delete alias."""
    try:
        alr = admin_models.AliasRecipient.objects.get(
            address="{}@autoreply.{}".format(
                instance.full_address, instance.domain))
    except admin_models.AliasRecipient.DoesNotExist:
        return
    alias = alr.alias
    alr.delete()
    if not alias.recipients_count:
        alias.delete()

@@ -466,32 +466,33 @@
          domain=
+u
 %22autoreply.%7B%7D%22.f
@@ -528,16 +528,16 @@
 reply:%22%0A
-
         
@@ -715,32 +715,33 @@
 %0A        domain=
+u
 %22autoreply.%25s%22 %25
@@ -739,22 +739,27 @@
 ply.
-%25s%22 %25 
+%7B%7D%22.format(
 oldname)
 .upd
@@ -754,16 +754,17 @@
 oldname)
+)
 .update(
@@ -775,32 +775,33 @@
          domain=
+u
 %22autoreply.%25s%22 %25
@@ -799,14 +799,19 @@
 ply.
-%25s%22 %25 
+%7B%7D%22.format(
 inst
@@ -816,24 +816,25 @@
 stance.name)
+)
 %0A    qset = 
@@ -1838,32 +1838,33 @@
         address=
+u
 %22%7B%7D@autoreply.%7B%7D
@@ -2164,16 +2164,17 @@
 ontains=
+u
 %22%7B%7D@auto
@@ -2221,32 +2221,33 @@
         address=
+u
 %22%7B%7D@autoreply.%7B%7D
@@ -2519,16 +2519,16 @@
 ts.get(%0A
-
         
@@ -2539,16 +2539,17 @@
 address=
+u
 %22%7B%7D@auto

Support unicode email addresses.