"""
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.decorators import login_required
from django.http import HttpRequest
from django.shortcuts import get_object_or_404
from django.urls import reverse

from compensation.forms.modals.state import NewCompensationStateModalForm, RemoveCompensationStateModalForm, \
    EditCompensationStateModalForm
from compensation.models import CompensationState
from ema.models import Ema
from konova.decorators import conservation_office_group_required, shared_access_required
from konova.utils.message_templates import COMPENSATION_STATE_ADDED, COMPENSATION_STATE_REMOVED, \
    COMPENSATION_STATE_EDITED


@login_required
@conservation_office_group_required
@shared_access_required(Ema, "id")
def state_new_view(request: HttpRequest, id: str):
    """ Renders a form for adding new states for an EMA

    Args:
        request (HttpRequest): The incoming request
        id (str): The EMA's id to which the new state will be related

    Returns:

    """
    ema = get_object_or_404(Ema, id=id)
    form = NewCompensationStateModalForm(request.POST or None, instance=ema, request=request)
    return form.process_request(
        request,
        msg_success=COMPENSATION_STATE_ADDED,
        redirect_url=reverse("ema:detail", args=(id,)) + "#related_data"
    )


@login_required
@conservation_office_group_required
@shared_access_required(Ema, "id")
def state_remove_view(request: HttpRequest, id: str, state_id: str):
    """ Renders a form for removing an EMA state

    Args:
        request (HttpRequest): The incoming request
        id (str): The ema id
        state_id (str): The state's id

    Returns:

    """
    ema = get_object_or_404(Ema, id=id)
    state = get_object_or_404(CompensationState, id=state_id)
    form = RemoveCompensationStateModalForm(request.POST or None, instance=ema, state=state, request=request)
    return form.process_request(
        request,
        msg_success=COMPENSATION_STATE_REMOVED,
        redirect_url=reverse("ema:detail", args=(id,)) + "#related_data"
    )


@login_required
@conservation_office_group_required
@shared_access_required(Ema, "id")
def state_edit_view(request: HttpRequest, id: str, state_id: str):
    """ Renders a form for editing an EMA state

    Args:
        request (HttpRequest): The incoming request
        id (str): The ema id
        state_id (str): The state's id

    Returns:

    """
    ema = get_object_or_404(Ema, id=id)
    state = get_object_or_404(CompensationState, id=state_id)
    form = EditCompensationStateModalForm(request.POST or None, instance=ema, state=state, request=request)
    return form.process_request(
        request,
        msg_success=COMPENSATION_STATE_EDITED,
        redirect_url=reverse("ema:detail", args=(id,)) + "#related_data"
    )

