"""
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 pgettext_lazy as _con, gettext_lazy as _

from konova.forms.modals import RemoveModalForm, BaseModalForm
from konova.utils import validators
from konova.utils.message_templates import PAYMENT_EDITED


class NewPaymentForm(BaseModalForm):
    """ Form handling payment related input

    """
    amount = forms.DecimalField(
        min_value=0.00,
        decimal_places=2,
        label=_con("money", "Amount"),  # contextual translation
        label_suffix=_(""),
        help_text=_("in Euro"),
        widget=forms.NumberInput(
            attrs={
                "class": "form-control",
                "placeholder": "0,00",
            }
        )
    )
    due = forms.DateField(
        label=_("Due on"),
        label_suffix=_(""),
        required=False,
        validators=[validators.reasonable_date],
        help_text=_("Due on which date"),
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
                "class": "form-control",
            },
            format="%d.%m.%Y"
        )
    )
    comment = forms.CharField(
        max_length=200,
        required=False,
        label=_("Comment"),
        label_suffix=_(""),
        help_text=_("Additional comment, maximum {} letters").format(200),
        widget=forms.Textarea(
            attrs={
                "rows": 5,
                "class": "form-control"
            }
        )
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.intervention = self.instance
        self.form_title = _("Payment")
        self.form_caption = _("Add a payment for intervention '{}'").format(self.intervention.title)

    def is_valid(self):
        """
        Checks on form validity.

        For this form we need to make sure that a date or a comment is set.
        If both are missing, the user needs to enter at least an explanation why
        there is no date to be entered.

        Returns:
            is_valid (bool): True if valid, False otherwise
        """
        super_valid = super().is_valid()
        if not super_valid:
            return super_valid

        date = self.cleaned_data.get("due", None)
        comment = self.cleaned_data.get("comment", None)
        if not date and not comment:
            # At least one needs to be set!
            self.add_error(
                "comment",
                _("If there is no date you can enter, please explain why.")
            )
            return False
        return super_valid

    def save(self):
        pay = self.instance.add_payment(self)
        return pay


class EditPaymentModalForm(NewPaymentForm):
    """ Form handling edit for Payment

    """
    payment = None

    def __init__(self, *args, **kwargs):
        self.payment = kwargs.pop("payment", None)
        super().__init__(*args, **kwargs)
        self.form_title = _("Edit payment")
        form_date = {
            "amount": self.payment.amount,
            "due": str(self.payment.due_on),
            "comment": self.payment.comment,
        }
        self.load_initial_data(form_date, disabled_fields=[])

    def save(self):
        payment = self.payment
        payment.amount = self.cleaned_data.get("amount", None)
        payment.due_on = self.cleaned_data.get("due", None)
        payment.comment = self.cleaned_data.get("comment", None)
        payment.save()
        self.instance.mark_as_edited(self.user, self.request, edit_comment=PAYMENT_EDITED)
        self.instance.send_data_to_egon()
        return payment


class RemovePaymentModalForm(RemoveModalForm):
    """ Removing modal form for Payment

    Can be used for anything, where removing shall be confirmed by the user a second time.

    """
    payment = None

    def __init__(self, *args, **kwargs):
        payment = kwargs.pop("payment", None)
        self.payment = payment
        super().__init__(*args, **kwargs)

    def save(self):
        self.instance.remove_payment(self)
