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

"""
from django import forms
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 RecordableObjectMixin


class RecordModalForm(BaseModalForm):
    """ Modal form for recording data

    """
    confirm = forms.BooleanField(
        label=_("Confirm record"),
        label_suffix="",
        widget=forms.CheckboxInput(),
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.form_title = _("Record data")
        self.form_caption = _("I, {} {}, confirm that all necessary control steps have been performed by myself.").format(self.user.first_name, self.user.last_name)
        # Disable automatic w-100 setting for this type of modal form. Looks kinda strange
        self.fields["confirm"].widget.attrs["class"] = ""

        if self.instance.recorded:
            # unrecord!
            self.fields["confirm"].label = _("Confirm unrecord")
            self.form_title = _("Unrecord data")
            self.form_caption = _("I, {} {}, confirm that this data must be unrecorded.").format(self.user.first_name, self.user.last_name)

        if not isinstance(self.instance, RecordableObjectMixin):
            raise NotImplementedError

    def is_valid(self):
        """ Checks for instance's validity and data quality

        Returns:

        """
        from intervention.models import Intervention
        super_val = super().is_valid()
        if self.instance.recorded:
            # If user wants to unrecord an already recorded dataset, we do not need to perform custom checks
            return super_val
        checker = self.instance.quality_check()
        for msg in checker.messages:
            self.add_error(
                "confirm",
                msg
            )
        valid = checker.valid
        # Special case: Intervention
        # Add direct checks for related compensations
        if isinstance(self.instance, Intervention):
            comps_valid = self._are_compensations_valid()
            valid = valid and comps_valid
        return super_val and valid

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

        Returns:

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

    def _are_compensations_valid(self):
        """ Runs a special case for intervention-compensations validity

        Returns:

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

        deductions_valid = self._are_deductions_valid()

        return comps_valid and deductions_valid

    def save(self):
        with transaction.atomic():
            if self.cleaned_data["confirm"]:
                if self.instance.recorded:
                    self.instance.set_unrecorded(self.user)
                else:
                    self.instance.set_recorded(self.user)
        return self.instance

    def check_for_recorded_instance(self):
        """ Overwrite the check method for doing nothing on the RecordModalForm

        Returns:

        """
        pass
