"""Postfix autoreply models."""

from django.db import models
from django.utils import timezone
from django.utils.formats import localize
from django.utils.translation import gettext_lazy as _

from modoboa.admin.models import Mailbox
from modoboa.sievefilters.lib import SieveClient


class ARmessage(models.Model):
    """Auto reply messages."""

    mbox = models.ForeignKey(Mailbox, on_delete=models.CASCADE)
    subject = models.CharField(
        _("subject"),
        max_length=255,
        help_text=_("The subject that will appear in sent emails"),
    )
    content = models.TextField(
        _("content"), help_text=_("The content that will appear in sent emails")
    )
    enabled = models.BooleanField(
        _("enabled"), help_text=_("Activate/Deactivate your auto reply"), default=False
    )
    fromdate = models.DateTimeField(default=timezone.now)
    untildate = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "postfix_autoreply_armessage"

    def __str__(self):
        return f"AR<{self.mbox}>: {self.enabled}"

    def update_sieve_rule(self, request, fset):
        context = {"name": self.mbox.user.fullname}
        days = request.localconfig.parameters.get_value("tracking_period")
        context["fromdate"] = localize(self.fromdate)
        fromdate = self.fromdate.isoformat()
        datepart = fromdate[:-6]
        tz = fromdate[-6:].replace(":", "")
        condition = [("currentdate", ":zone", tz, ":value", "ge", "iso8601", datepart)]
        if self.untildate:
            context["untildate"] = localize(self.untildate)
            condition.append(
                (
                    "currentdate",
                    ":zone",
                    tz,
                    ":value",
                    "lt",
                    "iso8601",
                    self.untildate.isoformat()[:-6],
                )
            )
        content = self.content % context
        name = "autoreply"
        action = [("vacation", ":subject", self.subject, ":days", days, content)]
        if not fset.getfilter(name):
            fset.addfilter(name, condition, action, matchtype="allof")
        else:
            fset.updatefilter(name, name, condition, action, matchtype="allof")
        for filter in fset.filters:
            if filter["name"] == name:
                filter["description"] = (
                    "Autoreply rule generated by Modoboa, do not edit!"
                )

    def manage_sieve_rule(self, request):
        client = SieveClient(user=request.user.username, password=str(request.auth))
        active_script, scripts = client.listscripts()
        if not active_script:
            active_script = "DefaultScript"
            client.pushscript(active_script, "# Empty script", True)
        fset = client.getscript(active_script, format="fset")
        if self.enabled:
            self.update_sieve_rule(request, fset)
        else:
            fset.removefilter("autoreply")
        client.pushscript(fset.name, str(fset))
