"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 04.12.20

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

from compensation.models import Payment
from konova.forms import BaseForm, BaseModalForm


class NewCompensationForm(BaseForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


class NewPaymentForm(BaseModalForm):
    amount = forms.DecimalField(
        min_value=0.00,
        decimal_places=2,
        label=_("Amount"),
        label_suffix=_(""),
        help_text=_("Amount in Euro"),
    )
    due = forms.DateField(
        label=_("Due on"),
        label_suffix=_(""),
        help_text=_("Due on which date"),
        widget=forms.DateInput(
            attrs={
                "type": "date",
                "data-provide": "datepicker",
            },
            format="%d.%m.%Y"
        )
    )
    transfer_note = forms.CharField(
        max_length=1000,
        required=False,
        label_suffix=_(""),
        label=_("Transfer note"),
        help_text=_("Note for money transfer")
    )

    def __init__(self, *args, **kwargs):
        self.template = "modal/modal_form.html"
        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 save(self):
        with transaction.atomic():
            pay = Payment.objects.create(
                created_by=self.user,
                amount=self.cleaned_data.get("amount", -1),
                due_on=self.cleaned_data.get("due", None),
                comment=self.cleaned_data.get("transfer_note", None),
                intervention=self.intervention,
            )
            return pay