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

"""
from bootstrap_modal_forms.forms import BSModalForm
from bootstrap_modal_forms.mixins import is_ajax
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpRequest
from django.shortcuts import render
from django.utils.translation import gettext_lazy as _

from konova.contexts import BaseContext
from konova.forms.base_form import BaseForm
from konova.utils.message_templates import FORM_INVALID


class BaseModalForm(BaseForm, BSModalForm):
    """ A specialzed form class for modal form handling

    """
    is_modal_form = True
    render_submit = True
    template = "modal/modal_form.html"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.action_btn_label = _("Continue")

    def process_request(self, request: HttpRequest, msg_success: str = _("Object removed"), msg_error: str = FORM_INVALID, redirect_url: str = None):
        """ Generic processing of request

        Wraps the request processing logic, so we don't need the same code everywhere a RemoveModalForm is being used

        Args:
            request (HttpRequest): The incoming request
            msg_success (str): The message in case of successful removing
            msg_error (str): The message in case of an error

        Returns:

        """
        redirect_url = redirect_url if redirect_url is not None else request.META.get("HTTP_REFERER", "home")
        template = self.template
        if request.method == "POST":
            if self.is_valid():
                if not is_ajax(request.META):
                    # Modal forms send one POST for checking on data validity. This can be used to return possible errors
                    # on the form. A second POST (if no errors occured) is sent afterwards and needs to process the
                    # saving/commiting of the data to the database. is_ajax() performs this check. The first request is
                    # an ajax call, the second is a regular form POST.
                    self.save()
                    messages.success(
                        request,
                        msg_success
                    )
                return HttpResponseRedirect(redirect_url)
            else:
                context = {
                    "form": self,
                }
                context = BaseContext(request, context).context
                return render(request, template, context)
        elif request.method == "GET":
            context = {
                "form": self,
            }
            context = BaseContext(request, context).context
            return render(request, template, context)
        else:
            raise NotImplementedError
