# Copyright (C) 2018-2025 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later

import json

from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView
from django.views.generic.list import ListView
from django_tables2.views import MultiTableMixin
from permission.backends import PermissionBackend
from permission.views import ProtectQuerysetMixin

from .models import Wrapped
from .tables import WrappedTable


class WrappedListView(ProtectQuerysetMixin, LoginRequiredMixin, MultiTableMixin, ListView):
    """
    Display all Wrapped, and classify by year
    """
    model = Wrapped
    tables = [
        lambda data: WrappedTable(data, prefix="public-"),
        lambda data: WrappedTable(data, prefix="personnal-"),
    ]
    template_name = 'wrapped/wrapped_list.html'
    extra_context = {'title': _("List of wrapped")}

    def get_queryset(self, **kwargs):
        return super().get_queryset(**kwargs).distinct()

    def get_tables_data(self):
        return [
            Wrapped.objects.filter(public=True),
            Wrapped.objects
            .filter(PermissionBackend.filter_queryset(self.request, Wrapped, "change", field='public'))
            .distinct()
            .order_by("-bde__date_start")
        ]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        w = self.object_list.filter(note__noteclub__club__pk__gte=-1, public=False)
        if w:
            context['club_not_public'] = 'true'
        else:
            context['club_not_public'] = 'false'
        return context


class WrappedDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView):
    """
    View a wrapped
    """
    model = Wrapped
    template_name = 'wrapped/0/wrapped_view.html'  # by default

    def get(self, *args, **kwargs):
        bde_id = Wrapped.objects.get(pk=kwargs['pk']).bde.id
        note_type = 'user' if 'user' in Wrapped.objects.get(pk=kwargs['pk']).note.__dir__() else 'club'
        self.template_name = 'wrapped/' + str(bde_id) + '/wrapped_view_' + note_type + '.html'
        return super().get(*args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        d = json.loads(self.object.data_json)
        for key in d:
            context[key] = d[key]
        context['title'] = str(self.object)
        return context
