"""
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 django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.utils.translation import gettext_lazy as _

from konova.forms.modals.base_form import BaseModalForm
from konova.models import Resubmission
from konova.utils import validators


class ResubmissionModalForm(BaseModalForm):
    date = forms.DateField(
        label_suffix=_(""),
        label=_("Date"),
        help_text=_("When do you want to be reminded?"),
        validators=[validators.reasonable_date],
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
                "class": "form-control",
            },
            format="%d.%m.%Y"
        )
    )
    comment = forms.CharField(
        required=False,
        label=_("Comment"),
        label_suffix=_(""),
        help_text=_("Additional comment"),
        widget=forms.Textarea(
            attrs={
                "cols": 30,
                "rows": 5,
                "class": "form-control",
            }
        )
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Resubmission")
        self.form_caption = _("Set your resubmission for this entry.")
        self.action_url = None

        try:
            self.resubmission = self.instance.resubmissions.get(
                user=self.user
            )
            self.initialize_form_field("date", str(self.resubmission.resubmit_on))
            self.initialize_form_field("comment", self.resubmission.comment)
        except ObjectDoesNotExist:
            self.resubmission = Resubmission()

    def is_valid(self):
        super_valid = super().is_valid()
        self_valid = True

        date = self.cleaned_data.get("date")
        today = datetime.date.today()
        if date <= today:
            self.add_error(
                "date",
                _("The date should be in the future")
            )
            self_valid = False

        return super_valid and self_valid

    def save(self):
        with transaction.atomic():
            self.resubmission.user = self.user
            self.resubmission.resubmit_on = self.cleaned_data.get("date")
            self.resubmission.comment = self.cleaned_data.get("comment")
            self.resubmission.save()
            self.instance.resubmissions.add(self.resubmission)
        return self.resubmission

    def check_for_recorded_instance(self):
        # Ignore logic in super() implementation
        return
