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

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

from .models import Wrapped


class WrappedTable(tables.Table):
    """
    List all wrapped
    """
    class Meta:
        attrs = {
            'class': 'table table-condensed table-striped table-hover',
            'id': 'wrapped_table'
        }
        row_attrs = {
            'class': lambda record: 'bg-danger' if not record.generated else '',
        }
        model = Wrapped
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('note', 'bde', 'public', )

    view = tables.LinkColumn(
        'wrapped:wrapped_detail',
        args=[A('pk')],
        attrs={
            'td': {'class': 'col-sm-2'},
            'a': {
                'class': 'btn btn-sm btn-primary',
                'data-turbolinks': 'false',
            }
        },
        text=_('view the wrapped'),
        accessor='pk',
        verbose_name=_('View'),
        orderable=False,
    )

    public = tables.Column(
        accessor="pk",
        orderable=False,
        attrs={
            "td": {
                "id": lambda record: "makepublic_" + str(record.pk),
                "class": 'col-sm-1',
                "data-toggle": "tooltip",
                "title": lambda record:
                (_("Click to make this wrapped private") if record.public else
                    _("Click to make this wrapped public")) if PermissionBackend.check_perm(
                    get_current_request(), "wrapped.change_wrapped_public", record) else None,
                "onclick": lambda record:
                'makepublic(' + str(record.id) + ', ' + str(not record.public).lower() + ')'
                if PermissionBackend.check_perm(get_current_request(), "wrapped.change_wrapped_public",
                                                record) else None
            }
        },
    )

    share = tables.Column(
        verbose_name=_("Share"),
        accessor="pk",
        orderable=False,
        attrs={
            "td": {
                "class": 'col-sm-2',
                "title": _("Click to copy the link in the press paper"),
            }
        },
    )

    def render_share(self, value, record):
        val = '<a class="btn btn-sm btn-primary" data-turbolinks="false" '
        val += 'onclick="copylink(' + str(record.id) + ')">'
        val += _('Copy link')
        val += '</a>'
        return format_html(val)

    def render_public(self, value, record):
        val = "✔" if record.public else "✖"
        return val