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

"""
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest, Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View

from intervention.models import Intervention
from konova.decorators import shared_access_required, default_group_required
from konova.forms.modals import RemoveModalForm
from konova.utils.message_templates import COMPENSATION_REMOVED_TEMPLATE


class RemoveCompensationFromInterventionView(LoginRequiredMixin, View):

    def __process_request(self, request: HttpRequest, id: str, comp_id: str, *args, **kwargs) -> HttpResponse:
        """ Renders a modal view for removing the compensation

        Args:
            request (HttpRequest): The incoming request
            id (str): The compensation's id

        Returns:

        """
        intervention = get_object_or_404(Intervention, id=id)
        try:
            comp = intervention.compensations.get(
                id=comp_id
            )
        except ObjectDoesNotExist:
            raise Http404("Unknown compensation")
        form = RemoveModalForm(request.POST or None, instance=comp, request=request)
        return form.process_request(
            request=request,
            msg_success=COMPENSATION_REMOVED_TEMPLATE.format(comp.identifier),
            redirect_url=reverse("intervention:detail", args=(id,)) + "#related_data",
        )

    @method_decorator(default_group_required)
    @method_decorator(shared_access_required(Intervention, "id"))
    def get(self, request, id: str, comp_id: str, *args, **kwargs) -> HttpResponse:
        return self.__process_request(request, id, comp_id, *args, **kwargs)

    @method_decorator(default_group_required)
    @method_decorator(shared_access_required(Intervention, "id"))
    def post(self, request, id: str, comp_id: str, *args, **kwargs) -> HttpResponse:
        return self.__process_request(request, id, comp_id, *args, **kwargs)