from django import template

from .models import Material
from .utils import text_color

register = template.Library()


@register.inclusion_tag("flashcards_grid.html")
def flashcards_grid(material_id=None):
    """Show flashcards as colored cards on any page.

    {% flashcards_grid %}                     newest material that has cards
    {% flashcards_grid material_id=3 %}       a specific material
    """
    materials = Material.objects.filter(cards__isnull=False).distinct().order_by("-created_at")

    if material_id and str(material_id).isdigit():
        material = Material.objects.filter(pk=int(material_id)).first()
    else:
        material = materials.first()

    cards = []
    if material:
        cards = [
            {
                "title": card.title,
                "content": card.content,
                "color": card.color,
                "fg": text_color(card.color),
            }
            for card in material.cards.all()
        ]

    return {"material": material, "cards": cards}