"""
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.base_form import BaseForm
from user.models import UserActionLogEntry, User


class RemoveForm(BaseForm):
    """ DEPRECATED

    NOT USED IN ANY PLACE.
    CAN BE DELETED AT SOME POINT.

    """
    check = forms.BooleanField(
        label=_("Confirm"),
        label_suffix=_(""),
        required=True,
    )

    def __init__(self, *args, **kwargs):
        self.object_to_remove = kwargs.pop("object_to_remove", None)
        self.remove_post_url = kwargs.pop("remove_post_url", "")
        self.cancel_url = kwargs.pop("cancel_url", "")

        super().__init__(*args, **kwargs)

        self.form_title = _("Remove")
        if self.object_to_remove is not None:
            self.form_caption = _("You are about to remove {} {}").format(self.object_to_remove.__class__.__name__, self.object_to_remove)
        self.action_url = self.remove_post_url
        self.cancel_redirect = self.cancel_url

    def is_checked(self) -> bool:
        return self.cleaned_data.get("check", False)

    def save(self, user: User):
        """ Perform generic removing by running the form typical 'save()' method

        Args:
            user (User): The performing user

        Returns:

        """
        if self.object_to_remove is not None and self.is_checked():
            with transaction.atomic():
                self.object_to_remove.is_active = False
                action = UserActionLogEntry.get_deleted_action(user)
                self.object_to_remove.deleted = action
                self.object_to_remove.save()
        return self.object_to_remove
