"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: ksp-servicestelle@sgdnord.rlp.de
Created on: 15.08.22

"""
from dateutil.utils import today
from django.apps import apps
from django.db import models

from konova.models import BaseResource
from konova.utils.mailer import Mailer


class Resubmission(BaseResource):
    user = models.ForeignKey(
        "user.User",
        on_delete=models.CASCADE,
        help_text="The user who wants to be notifed"
    )
    resubmit_on = models.DateField(
        help_text="On which date the resubmission should be performed"
    )
    resubmission_sent = models.BooleanField(
        default=False,
        help_text="Whether a resubmission has been sent or not"
    )
    comment = models.TextField(
        null=True,
        blank=True,
        help_text="Optional comment for the user itself"
    )

    def send_resubmission_mail(self, obj_id, obj_class):
        """ Sends a resubmission mail

        """
        obj_class = apps.get_model(obj_class[0], obj_class[1])
        obj = obj_class.objects.get(id=obj_id)
        municipal_names = list(obj.geometry.get_underlying_municipals().values_list("name", flat=True))

        _today = today().date()
        resubmission_handled = _today.__ge__(self.resubmit_on) and self.resubmission_sent
        if resubmission_handled:
            return

        mailer = Mailer()
        mailer.send_mail_resubmission(obj, self, municipal_names)
        self.resubmission_sent = True
        self.save()
