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

from konova.forms.modals import BaseModalForm


class CheckModalForm(BaseModalForm):
    """ The modal form for running a check on interventions and their compensations

    """
    checked_intervention = forms.BooleanField(
        label=_("Checked intervention data"),
        label_suffix="",
        widget=forms.CheckboxInput(),
        required=True,
    )
    checked_comps = forms.BooleanField(
        label=_("Checked compensations data and payments"),
        label_suffix="",
        widget=forms.CheckboxInput(),
        required=True
    )
    valid = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Run check")
        self.form_caption = _("The necessary control steps have been performed:").format(self.user.first_name, self.user.last_name)
        self.valid = False

    def _are_deductions_valid(self):
        """ Performs validity checks on deductions and their eco-account

        Returns:

        """
        deductions = self.instance.deductions.all()
        valid = True
        for deduction in deductions:
            checker = deduction.account.quality_check()
            for msg in checker.messages:
                self.add_error(
                    "checked_comps",
                    f"{deduction.account.identifier}: {msg}"
                )
            valid &= checker.valid
        return valid

    def _are_comps_valid(self):
        """ Performs validity checks on all types of compensations

        Types of compensations are
            * regular Compensations
            * deductions from EcoAccounts

        Returns:

        """
        comps = self.instance.compensations.filter(
            deleted=None,
        )
        comps_valid = True
        for comp in comps:
            checker = comp.quality_check()
            for msg in checker.messages:
                self.add_error(
                    "checked_comps",
                    f"{comp.identifier}: {msg}"
                )
            if comps_valid and not checker.valid:
                comps_valid = checker.valid
        deductions_valid = self._are_deductions_valid()
        return deductions_valid and comps_valid

    def is_valid(self) -> bool:
        """ Perform a validity check based on quality_check() logic

        Returns:
            result (bool)
        """
        super_valid = super().is_valid()
        # Perform check
        checker = self.instance.quality_check()
        for msg in checker.messages:
            self.add_error(
                "checked_intervention",
                msg
            )
        all_comps_valid = self._are_comps_valid()
        intervention_valid = checker.valid

        return super_valid and intervention_valid and all_comps_valid

    def save(self):
        """ Saving logic

        Returns:

        """
        with transaction.atomic():
            self.instance.set_checked(self.user)
