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

"""
import datetime

from compensation.models import Compensation, EcoAccount
from ema.models import Ema
from intervention.models import Intervention
from konova.management.commands.setup import BaseKonovaCommand
from konova.models import Resubmission


class Command(BaseKonovaCommand):
    help = "Checks for resubmissions due now"

    def handle(self, *args, **options):
        try:
            resubmitable_models = [
                Intervention,
                Compensation,
                Ema,
                EcoAccount,
            ]
            today = datetime.date.today()
            resubmissions = Resubmission.objects.filter(
                resubmit_on__lte=today,
                resubmission_sent=False,
            )
            self._write_warning(f"Found {resubmissions.count()} resubmission. Process now...")
            for model in resubmitable_models:
                all_objs = model.objects.filter(
                    resubmissions__in=resubmissions
                )
                self._write_warning(f"Process resubmissions for {all_objs.count()} {model.__name__} entries")
                for obj in all_objs:
                    obj.resubmit()
            self._write_success("Mails have been sent.")
            resubmissions = Resubmission.objects.filter(
                resubmission_sent=True,
            )
            resubmissions.delete()
            self._write_success("Resubmissions have been deleted.")
        except KeyboardInterrupt:
            self._break_line()
            exit(-1)