"""
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.db.models import Q
from django.http import HttpRequest
from django.shortcuts import render
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from compensation.models import EcoAccount, Compensation
from intervention.models import Intervention
from konova.contexts import BaseContext
from konova.decorators import any_group_check
from konova.sub_settings.context_settings import TAB_TITLE_IDENTIFIER
from news.models import ServerMessage


@login_required
@any_group_check
def home_view(request: HttpRequest):
    """
    Renders the landing page

    Args:
        request (HttpRequest): The used request object

    Returns:
        A redirect
    """
    template = "konova/home.html"
    now = timezone.now()
    user = request.user

    # Fetch the four newest active and published ServerMessages
    msgs = ServerMessage.objects.filter(
        is_active=True,
        publish_on__lte=now,
        unpublish_on__gte=now,
    ).order_by(
        "-publish_on"
    )[:3]

    # First fetch all valid objects (undeleted, only newest versions)
    interventions = Intervention.objects.filter(
        deleted=None,
    )
    # Then fetch only user related ones
    user_interventions = interventions.filter(
        Q(users__in=[user]) | Q(teams__in=user.shared_teams)
    ).distinct()

    # Repeat for other objects
    comps = Compensation.objects.filter(
        deleted=None,
    )
    user_comps = comps.filter(
        Q(intervention__users__in=[user]) | Q(intervention__teams__in=user.shared_teams)
    ).distinct()
    eco_accs = EcoAccount.objects.filter(
        deleted=None,
    )
    user_ecco_accs = eco_accs.filter(
        Q(users__in=[user]) | Q(teams__in=user.shared_teams)
    ).distinct()

    additional_context = {
        "msgs": msgs,
        "total_intervention_count": interventions.count(),
        "user_intervention_count": user_interventions.count(),
        "total_compensation_count": comps.count(),
        "user_compensation_count": user_comps.count(),
        "total_eco_count": eco_accs.count(),
        "user_eco_count": user_ecco_accs.count(),
        TAB_TITLE_IDENTIFIER: _("Home"),
    }
    context = BaseContext(request, additional_context).context
    return render(request, template, context)

