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

"""
from django import forms
from django.utils.translation import gettext_lazy as _

from konova.forms.modals import BaseModalForm
from konova.models import DeadlineType
from konova.utils.message_templates import DEADLINE_EDITED


class NewDeadlineModalForm(BaseModalForm):
    """ Form handling deadline related input

    """
    type = forms.ChoiceField(
        label=_("Deadline Type"),
        label_suffix="",
        required=True,
        help_text=_("Select the deadline type"),
        choices=DeadlineType.choices,
        widget=forms.Select(
            attrs={
                "class": "form-control"
            }
        )
    )
    date = forms.DateField(
        label=_("Date"),
        label_suffix="",
        required=True,
        help_text=_("Select date"),
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
                "class": "form-control",
            },
            format="%d.%m.%Y"
        )
    )
    comment = forms.CharField(
        required=False,
        max_length=200,
        label=_("Comment"),
        label_suffix=_(""),
        help_text=_("Additional comment, maximum {} letters").format(200),
        widget=forms.Textarea(
            attrs={
                "cols": 30,
                "rows": 5,
                "class": "form-control",
            }
        )
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("New deadline")
        self.form_caption = _("Insert data for the new deadline")

    def save(self):
        deadline = self.instance.add_deadline(self)
        return deadline


class EditDeadlineModalForm(NewDeadlineModalForm):
    deadline = None

    def __init__(self, *args, **kwargs):
        self.deadline = kwargs.pop("deadline", None)
        super().__init__(*args, **kwargs)
        self.form_title = _("Edit deadline")
        form_data = {
            "type": self.deadline.type,
            "date": str(self.deadline.date),
            "comment": self.deadline.comment,
        }
        self.load_initial_data(form_data)

    def save(self):
        deadline = self.deadline
        deadline.type = self.cleaned_data.get("type", None)
        deadline.date = self.cleaned_data.get("date", None)
        deadline.comment = self.cleaned_data.get("comment", None)
        deadline.save()
        self.instance.mark_as_edited(self.user, self.request, edit_comment=DEADLINE_EDITED)
        return deadline
