"""
Author: Michel Peltriaux
Created on: 14.12.25

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

from ema.models import Ema
from konova.contexts import BaseContext
from konova.forms import SimpleGeomForm
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 DO_NOT_FORGET_TO_SHARE
from konova.views.detail import AbstractDetailView


class DetailEmaView(AbstractDetailView):
    _TEMPLATE = "ema/detail/view.html"

    def get(self, request: HttpRequest, id: str, *args, **kwargs) -> HttpResponse:
        """ Renders the detail view of an EMA

        Args:
            request (HttpRequest): The incoming request
            id (str): The EMA id

        Returns:

        """
        ema = get_object_or_404(Ema, id=id, deleted=None)

        geom_form = SimpleGeomForm(instance=ema)
        parcels = ema.get_underlying_parcels()
        _user = request.user
        is_entry_shared = ema.is_shared_with(_user)

        # Order states according to surface
        before_states = ema.before_states.all().order_by("-surface")
        after_states = ema.after_states.all().order_by("-surface")

        # 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 = ema.get_surface_before_states()
        sum_after_states = ema.get_surface_after_states()
        diff_states = abs(sum_before_states - sum_after_states)

        ema.set_status_messages(request)

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

        context = {
            "obj": ema,
            "geom_form": geom_form,
            "parcels": parcels,
            "is_entry_shared": is_entry_shared,
            "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": ema.get_LANIS_link(),
            TAB_TITLE_IDENTIFIER: f"{ema.identifier} - {ema.title}",
            "has_finished_deadlines": ema.get_finished_deadlines().exists(),
        }
        context = BaseContext(request, context).context
        return render(request, self._TEMPLATE, context)
