# 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.translation import gettext_lazy as _
from note_kfet.middlewares import get_current_request
from note.templatetags.pretty_money import pretty_money
from permission.backends import PermissionBackend

from .models import Food, Dish, Order, Recipe


class FoodTable(tables.Table):
    """
    List all foods.
    """
    qr_code_numbers = tables.Column(empty_values=(), verbose_name=_("QR Codes"), orderable=False)

    date = tables.Column(empty_values=(), verbose_name=_("Arrival/creation date"), orderable=False)

    def render_date(self, record):
        if record.__class__.__name__ == "BasicFood":
            return record.arrival_date.strftime("%d/%m/%Y %H:%M")
        elif record.__class__.__name__ == "TransformedFood":
            return record.creation_date.strftime("%d/%m/%Y %H:%M")
        else:
            return "--"

    def render_qr_code_numbers(self, record):
        return ", ".join(str(q.qr_code_number) for q in record.QR_code.all())

    class Meta:
        model = Food
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('name', 'owner', 'qr_code_numbers', 'allergens', 'traces', 'date', 'expiry_date')
        row_attrs = {
            'class': 'table-row',
            'data-href': lambda record: 'detail/' + str(record.pk),
            'style': 'cursor:pointer',
        }


class DishTable(tables.Table):
    """
    List dishes
    """
    supplements = tables.Column(empty_values=(), verbose_name=_('Available supplements'), orderable=False)

    def render_supplements(self, record):
        return ", ".join(str(q.food) for q in record.supplements.all())

    def render_price(self, value):
        return pretty_money(value)

    class Meta:
        model = Dish
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('main', 'supplements', 'price', 'available')
        row_attrs = {
            'class': 'table-row',
            'data-href': lambda record: str(record.pk),
            'style': 'cursor:pointer',
        }


DELETE_TEMPLATE = """
<button id="{{ record.pk }}"
        class="btn btn-danger btn-sm"
        onclick="delete_button(this.id, 'orders_table_{{ table.prefix }}')">
    {{ delete_trans }}
</button>
"""


SERVE_TEMPLATE = """
<button id="{{ record.pk }}"
        class="btn btn-sm {% if record.served %}btn-secondary{% else %}btn-success{% endif %}"
        onclick="serve_button(this.id, 'orders_table_{{ table.prefix }}', {{ record.served|yesno:'true,false' }})">
    {% if record.served %}
        {{ record.served_at|date:"d/m/Y H:i" }}
    {% else %}""" + _('Serve') + """
    {% endif %}
</button>
"""


class OrderTable(tables.Table):
    """
    Lis all orders.
    """
    delete = tables.TemplateColumn(
        template_code=DELETE_TEMPLATE,
        extra_context={"delete_trans": _('Delete')},
        orderable=False,
        attrs={'td': {'class': lambda record: 'col-sm-1' + (
            ' d-none' if not PermissionBackend.check_perm(
                get_current_request(), "food.delete_order",
                record) else '')}}, verbose_name=_("Delete"), )

    serve = tables.TemplateColumn(
        template_code=SERVE_TEMPLATE,
        extra_context={"serve_trans": _('Serve')},
        orderable=False,
        attrs={'td': {'class': lambda record: 'col-sm-1' + (
            ' d-none' if not PermissionBackend.check_perm(
                get_current_request(), "food.change_order_saved",
                record) else '')}}, verbose_name=_("Serve"), )

    class Meta:
        model = Order
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('number', 'ordered_at', 'user', 'dish', 'supplements', 'request', 'serve', 'delete')
        order_by = ('ordered_at', )
        row_attrs = {
            'class': 'table-row',
            'style': 'cursor:pointer',
        }


class RecipeTable(tables.Table):
    """
    List all recipes
    """
    def render_ingredients(self, record):
        return ", ".join(str(q) for q in record.ingredients)

    class Meta:
        model = Recipe
        template_name = 'django_tables2/bootstrap4.html'
        fields = ('name', 'creater', 'ingredients',)
        row_attrs = {
            'class': 'table-row',
            'data-href': lambda record: str(record.pk),
            'style': 'cursor:pointer',
        }
