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

"""
from django.http import HttpRequest
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from compensation.models import Compensation
from konova.contexts import BaseContext
from konova.decorators import uuid_required
from konova.forms import SimpleGeomForm
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from konova.utils.generators import generate_qr_code

@uuid_required
def report_view(request: HttpRequest, id: str):
    """ Renders the public report view

    Args:
        request (HttpRequest): The incoming request
        id (str): The id of the intervention

    Returns:

    """
    # Reuse the compensation report template since compensations are structurally identical
    template = "compensation/report/compensation/report.html"
    comp = get_object_or_404(Compensation, id=id)

    tab_title = _("Report {}").format(comp.identifier)
    # If intervention is not recorded (yet or currently) we need to render another template without any data
    if not comp.is_ready_for_publish():
        template = "report/unavailable.html"
        context = {
            TAB_TITLE_IDENTIFIER: tab_title,
        }
        context = BaseContext(request, context).context
        return render(request, template, context)

    # Prepare data for map viewer
    geom_form = SimpleGeomForm(
        instance=comp
    )
    parcels = comp.get_underlying_parcels()

    qrcode_url = request.build_absolute_uri(reverse("compensation:report", args=(id,)))
    qrcode_img = generate_qr_code(qrcode_url, 10)
    qrcode_lanis_url = comp.get_LANIS_link()
    qrcode_img_lanis = generate_qr_code(qrcode_lanis_url, 7)

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

    context = {
        "obj": comp,
        "qrcode": {
            "img": qrcode_img,
            "url": qrcode_url,
        },
        "qrcode_lanis": {
            "img": qrcode_img_lanis,
            "url": qrcode_lanis_url,
        },
        "is_entry_shared": False,  # disables action buttons during rendering
        "before_states": before_states,
        "after_states": after_states,
        "geom_form": geom_form,
        "parcels": parcels,
        "actions": actions,
        "tables_scrollable": False,
        TAB_TITLE_IDENTIFIER: tab_title,
    }
    context = BaseContext(request, context).context
    return render(request, template, context)
