"""
Author: Michel Peltriaux
Created on: 14.12.25

"""
from django.contrib import messages
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, get_object_or_404

from compensation.models import Compensation
from konova.contexts import BaseContext
from konova.forms import SimpleGeomForm
from konova.settings import ETS_GROUP, ZB_GROUP, DEFAULT_GROUP
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from konova.utils.message_templates import DO_NOT_FORGET_TO_SHARE, DATA_CHECKED_PREVIOUSLY_TEMPLATE
from konova.views.detail import AbstractDetailView


class DetailCompensationView(AbstractDetailView):
    _TEMPLATE = "compensation/detail/compensation/view.html"

    def get(self, request: HttpRequest, id: str, *args, **kwargs) -> HttpResponse:

        """ Renders a detail view for a compensation

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

        Returns:

        """
        comp = get_object_or_404(
            Compensation.objects.select_related(
                "modified",
                "created",
                "geometry"
            ),
            id=id,
            deleted=None,
            intervention__deleted=None,
        )
        geom_form = SimpleGeomForm(instance=comp)
        parcels = comp.get_underlying_parcels()
        _user = request.user
        is_data_shared = comp.intervention.is_shared_with(_user)

        # Order states according to surface
        before_states = comp.before_states.all().prefetch_related("biotope_type").order_by("-surface")
        after_states = comp.after_states.all().prefetch_related("biotope_type").order_by("-surface")
        actions = comp.actions.all().prefetch_related("action_type")

        # Precalculate logical errors between before- and after-states
        # Sum() returns None in case of no states, so we catch that and replace it with 0 for easier handling
        sum_before_states = comp.get_surface_before_states()
        sum_after_states = comp.get_surface_after_states()
        diff_states = abs(sum_before_states - sum_after_states)

        request = comp.set_status_messages(request)

        last_checked = comp.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
            )

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

        context = {
            "obj": comp,
            "last_checked": last_checked,
            "last_checked_tooltip": last_checked_tooltip,
            "geom_form": geom_form,
            "parcels": parcels,
            "is_entry_shared": is_data_shared,
            "actions": actions,
            "before_states": before_states,
            "after_states": after_states,
            "sum_before_states": sum_before_states,
            "sum_after_states": sum_after_states,
            "diff_states": diff_states,
            "is_default_member": _user.in_group(DEFAULT_GROUP),
            "is_zb_member": _user.in_group(ZB_GROUP),
            "is_ets_member": _user.in_group(ETS_GROUP),
            "LANIS_LINK": comp.get_LANIS_link(),
            TAB_TITLE_IDENTIFIER: f"{comp.identifier} - {comp.title}",
            "has_finished_deadlines": comp.get_finished_deadlines().exists(),
        }
        context = BaseContext(request, context).context
        return render(request, self._TEMPLATE, context)