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

import django_tables2 as tables
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django_tables2 import A
from django.urls import reverse, reverse_lazy
from note_kfet.middlewares import get_current_request
from permission.backends import PermissionBackend

from .models import Achievement, Challenge, Family, FamilyMembership


class FamilyTable(tables.Table):
    """
    List all families
    """

    description = tables.Column(verbose_name=_("Description"))

    class Meta:
        attrs = {
            'class': 'table table-condensed table-striped table-hover'
        }
        model = Family
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('name', 'score', 'rank',)
        order_by = ('rank',)
        row_attrs = {
            'class': 'table-row',
            'data-href': lambda record: reverse('family:family_detail', args=[record.pk]),
            'style': 'cursor:pointer',
        }


class ChallengeTable(tables.Table):
    """
    List all challenges
    """

    name = tables.Column(verbose_name=_("Name"))
    description = tables.Column(verbose_name=_("Description"))
    points = tables.Column(verbose_name=_("Points"))

    class Meta:
        attrs = {
            'class': 'table table-condensed table-striped table-hover'
        }
        order_by = ('id',)
        model = Challenge
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('name', 'description', 'points',)
        row_attrs = {
            'class': 'table-row',
            'data-href': lambda record: reverse('family:challenge_detail', args=[record.pk]),
            'style': 'cursor:pointer',
        }


class FamilyMembershipTable(tables.Table):
    """
    List all family memberships.
    """

    def render_user(self, value):
        # Display user's name, clickable if permission is granted
        s = value.username
        if PermissionBackend.check_perm(get_current_request(), "auth.view_user", value):
            s = format_html("<a href='{url}'>{name}</a>",
                            url=reverse_lazy('member:user_detail', kwargs={"pk": value.pk}), name=s)
        return s

    class Meta:
        attrs = {
            'class': 'table table-condensed table-striped',
            'style': 'table-layout: fixed;'
        }
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('user',)
        model = FamilyMembership


class AchievementTable(tables.Table):
    """
    List recent achievements.
    """

    challenge = tables.Column(verbose_name=_("Challenge"))

    validate = tables.LinkColumn(
        'family:achievement_validate',
        args=[A('id')],
        verbose_name=_("Validate"),
        text=_("Validate"),
        orderable=False,
        attrs={
            'th': {
                'id': 'validate-achievement-header'
            },
            'a': {
                'class': 'btn btn-success',
                'data-type': 'validate-achievement'
            }
        },
    )

    delete = tables.LinkColumn(
        'family:achievement_delete',
        args=[A('id')],
        verbose_name=_("Delete"),
        text=_("Delete"),
        orderable=False,
        attrs={
            'th': {
                'id': 'delete-achievement-header'
            },
            'a': {
                'class': 'btn btn-danger',
                'data-type': 'delete-achievement'
            }
        },
    )

    class Meta:
        attrs = {
            'class': 'table table-condensed table-striped table-hover'
        }
        model = Achievement
        fields = ('family', 'challenge', 'challenge__points', 'obtained_at', 'valid')
        template_name = 'django_tables2/bootstrap4.html'
        order_by = ('-obtained_at',)


class FamilyAchievementTable(tables.Table):
    """
    Table des défis réalisés par une famille spécifique.
    """

    challenge = tables.Column(verbose_name=_("Challenge"))

    class Meta:
        model = Achievement
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('challenge', 'challenge__points', 'obtained_at', 'valid')
        attrs = {
            'class': 'table table-condensed table-striped table-hover'
        }
        order_by = ('-obtained_at',)
