from django import template
from cards.models import Card

register = template.Library()

@register.inclusion_tag('templatetags/card_multiselect.html')
def card_multiselect(field_name, label, placeholder, cards=None, selected_values=None, cache_timeout=86400):
    """
    Renders a multiselect field for choosing cards while supporting quantity data.
    
    Updated to allow `card_filter` to be either a dictionary (of lookup parameters) or a QuerySet.
    This is useful when you want to limit available cards based on your new trades models (e.g. showing only
    cards that appear in active trade offers).
    
    Parameters:
      - field_name: The name attribute for the select tag.
      - label: Label text to show above the selector.
      - placeholder: Placeholder text to show in the select.
      - selected_values: (Optional) A list of selected values; if a value includes a quantity it should be in the format "card_id:quantity".
      - cache_timeout: (Optional) Cache timeout (in seconds) for the options block.
      - cache_key: (Optional) Cache key.
    """
    if selected_values is None:
        selected_values = []
    # Create a mapping {card_id: quantity}
    selected_cards = {}
    for val in selected_values:
        parts = str(val).split(':')
        card_id = parts[0]
        quantity = parts[1] if len(parts) > 1 else 1
        selected_cards[card_id] = quantity

    if cards is None:
       cards = Card.objects.all()

    # Loop through available cards and attach pre‑selected quantity
    for card in cards:
        pk_str = str(card.pk)
        if pk_str in selected_cards:
            card.selected_quantity = selected_cards[pk_str]
            card.selected = True
        else:
            card.selected_quantity = 1
            card.selected = False

    return {
        'field_name': field_name,
        'field_id': field_name,  # using the name as id for simplicity
        'label': label,
        'cards': cards,
        'placeholder': placeholder,
        'selected_values': list(selected_cards.keys()),
        'cache_timeout': cache_timeout
    }