"""
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.mixins import LoginRequiredMixin
from django.db.models import Q
from django.http import HttpRequest
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views import View

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


class HomeView(LoginRequiredMixin, View):

    @method_decorator(any_group_check)
    def get(self, request: HttpRequest):
        """
        Renders the landing page

        Args:
            request (HttpRequest): The used request object

        Returns:
            A redirect
        """
        template = "konova/home.html"
        user = request.user
        user_teams = user.shared_teams

        # Fetch the four newest active and published ServerMessages
        msgs = ServerMessage.get_current_news()[: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_teams)
        ).distinct()

        # Repeat for other objects
        comps = Compensation.objects.filter(
            deleted=None,
            intervention__deleted=None,
        )
        user_comps = comps.filter(
            Q(intervention__users__in=[user]) | Q(intervention__teams__in=user_teams)
        ).distinct()
        eco_accs = EcoAccount.objects.filter(
            deleted=None,
        )
        user_ecco_accs = eco_accs.filter(
            Q(users__in=[user]) | Q(teams__in=user_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)

