"""
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 import messages
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpRequest
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from intervention.forms.intervention import EditInterventionForm, NewInterventionForm
from intervention.models import Intervention
from intervention.tables import InterventionTable
from konova.contexts import BaseContext
from konova.decorators import default_group_required, shared_access_required, any_group_check, login_required_modal
from konova.forms import SimpleGeomForm
from konova.forms.modals import RemoveModalForm
from konova.settings import DEFAULT_GROUP, ZB_GROUP, ETS_GROUP
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from konova.utils.message_templates import DATA_CHECKED_PREVIOUSLY_TEMPLATE, RECORDED_BLOCKS_EDIT, \
    CHECKED_RECORDED_RESET, FORM_INVALID, IDENTIFIER_REPLACED, DO_NOT_FORGET_TO_SHARE
from konova.utils.user_checks import in_group


@login_required
@any_group_check
def index_view(request: HttpRequest):
    """
    Renders the index view for Interventions

    Args:
        request (HttpRequest): The incoming request

    Returns:
        A rendered view
    """
    template = "generic_index.html"

    # Filtering by user access is performed in table filter inside of InterventionTableFilter class
    interventions = Intervention.objects.filter(
        deleted=None,  # not deleted
    ).select_related(
        "legal"
    ).order_by(
        "-modified__timestamp"
    )
    table = InterventionTable(
        request=request,
        queryset=interventions
    )
    context = {
        "table": table,
        TAB_TITLE_IDENTIFIER: _("Interventions - Overview"),
    }
    context = BaseContext(request, context).context
    return render(request, template, context)


@login_required
@default_group_required
def new_view(request: HttpRequest):
    """
    Renders a view for a new intervention creation

    Args:
        request (HttpRequest): The incoming request

    Returns:

    """
    template = "intervention/form/view.html"
    data_form = NewInterventionForm(request.POST or None)
    geom_form = SimpleGeomForm(request.POST or None, read_only=False)
    if request.method == "POST":
        if data_form.is_valid() and geom_form.is_valid():
            generated_identifier = data_form.cleaned_data.get("identifier", None)
            intervention = data_form.save(request.user, geom_form)
            if generated_identifier != intervention.identifier:
                messages.info(
                    request,
                    IDENTIFIER_REPLACED.format(
                        generated_identifier,
                        intervention.identifier
                    )
                )
            messages.success(request, _("Intervention {} added").format(intervention.identifier))
            return redirect("intervention:detail", id=intervention.id)
        else:
            messages.error(request, FORM_INVALID, extra_tags="danger",)
    else:
        # For clarification: nothing in this case
        pass
    context = {
        "form": data_form,
        "geom_form": geom_form,
        TAB_TITLE_IDENTIFIER: _("New intervention"),
    }
    context = BaseContext(request, context).context
    return render(request, template, context)


@login_required
@default_group_required
def new_id_view(request: HttpRequest):
    """ JSON endpoint

    Provides fetching of free identifiers for e.g. AJAX calls

    """
    tmp_intervention = Intervention()
    identifier = tmp_intervention.generate_new_identifier()
    while Intervention.objects.filter(identifier=identifier).exists():
        identifier = tmp_intervention.generate_new_identifier()
    return JsonResponse(
        data={
            "gen_data": identifier
        }
    )


@login_required
@any_group_check
def detail_view(request: HttpRequest, id: str):
    """ Renders a detail view for viewing an intervention's data

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

    Returns:

    """
    template = "intervention/detail/view.html"

    # Fetch data, filter out deleted related data
    intervention = get_object_or_404(
        Intervention.objects.select_related(
            "geometry",
            "legal",
            "responsible",
        ).prefetch_related(
            "legal__revocations",
        ),
        id=id,
        deleted=None
    )
    compensations = intervention.compensations.filter(
        deleted=None,
    )
    _user = request.user
    is_data_shared = intervention.is_shared_with(user=_user)

    geom_form = SimpleGeomForm(
        instance=intervention,
    )
    last_checked = intervention.get_last_checked_action()
    last_checked_tooltip = ""
    if last_checked:
        last_checked_tooltip = DATA_CHECKED_PREVIOUSLY_TEMPLATE.format(
            last_checked.get_timestamp_str_formatted(),
            last_checked.user
        )

    has_payment_without_document = intervention.payments.exists() and not intervention.get_documents()[1].exists()

    requesting_user_is_only_shared_user = intervention.is_only_shared_with(_user)
    if requesting_user_is_only_shared_user:
        messages.info(
            request,
            DO_NOT_FORGET_TO_SHARE
        )

    context = {
        "obj": intervention,
        "last_checked": last_checked,
        "last_checked_tooltip": last_checked_tooltip,
        "compensations": compensations,
        "has_access": is_data_shared,
        "geom_form": geom_form,
        "is_default_member": in_group(_user, DEFAULT_GROUP),
        "is_zb_member": in_group(_user, ZB_GROUP),
        "is_ets_member": in_group(_user, ETS_GROUP),
        "LANIS_LINK": intervention.get_LANIS_link(),
        "has_payment_without_document": has_payment_without_document,
        TAB_TITLE_IDENTIFIER: f"{intervention.identifier} - {intervention.title}",
    }

    request = intervention.set_status_messages(request)

    context = BaseContext(request, context).context
    return render(request, template, context)


@login_required
@default_group_required
@shared_access_required(Intervention, "id")
def edit_view(request: HttpRequest, id: str):
    """
    Renders a view for editing interventions

    Args:
        request (HttpRequest): The incoming request

    Returns:

    """
    template = "intervention/form/view.html"
    # Get object from db
    intervention = get_object_or_404(Intervention, id=id)
    if intervention.is_recorded:
        messages.info(
            request,
            RECORDED_BLOCKS_EDIT
        )
        return redirect("intervention:detail", id=id)

    # Create forms, initialize with values from db/from POST request
    data_form = EditInterventionForm(request.POST or None, instance=intervention)
    geom_form = SimpleGeomForm(request.POST or None, read_only=False, instance=intervention)
    if request.method == "POST":
        if data_form.is_valid() and geom_form.is_valid():
            # The data form takes the geom form for processing, as well as the performing user
            # Save the current state of recorded|checked to inform the user in case of a status reset due to editing
            i_rec = intervention.recorded is not None
            i_check = intervention.checked is not None
            intervention = data_form.save(request.user, geom_form)
            messages.success(request, _("Intervention {} edited").format(intervention.identifier))
            if i_check or i_rec:
                messages.info(request, CHECKED_RECORDED_RESET)
            return redirect("intervention:detail", id=intervention.id)
        else:
            messages.error(request, FORM_INVALID, extra_tags="danger",)
    else:
        # For clarification: nothing in this case
        pass
    context = {
        "form": data_form,
        "geom_form": geom_form,
        TAB_TITLE_IDENTIFIER: _("Edit {}").format(intervention.identifier),
    }
    context = BaseContext(request, context).context
    return render(request, template, context)


@login_required_modal
@login_required
@default_group_required
@shared_access_required(Intervention, "id")
def remove_view(request: HttpRequest, id: str):
    """ Renders a remove view for this intervention

    Args:
        request (HttpRequest): The incoming request
        id (str): The uuid id as string

    Returns:

    """
    obj = Intervention.objects.get(id=id)
    identifier = obj.identifier
    form = RemoveModalForm(request.POST or None, instance=obj, request=request)
    return form.process_request(
        request,
        _("{} removed").format(identifier),
        redirect_url=reverse("intervention:index")
    )
