from django import template
from math import ceil
from trades.models import TradeAcceptance
register = template.Library()

@register.inclusion_tag('templatetags/trade_offer.html', takes_context=True)
def render_trade_offer(context, offer):
    """
    Renders a trade offer including detailed trade acceptance information.
    Freezes the through-model querysets to avoid extra DB hits.
    """
    trade_offer_have_cards = list(offer.trade_offer_have_cards.all())
    trade_offer_want_cards = list(offer.trade_offer_want_cards.all())

    have_cards_available = [
        card for card in trade_offer_have_cards
        if card.quantity > card.qty_accepted
    ]
    want_cards_available = [
        card for card in trade_offer_want_cards
        if card.quantity > card.qty_accepted
    ]

    acceptances = list(offer.acceptances.all())

    # Determine if the offer should show its back side (acceptances view) by default.
    # If either side has no available cards, then flip the offer.
    if not have_cards_available or not want_cards_available:
        flipped = True
    else:
        flipped = False

    return {
        'offer_pk': offer.pk,
        'flipped': flipped,  # new flag to control the default face
        'offer_hash': offer.hash,
        'rarity_icon': offer.rarity_icon,
        'initiated_by_email': offer.initiated_by.user.email,
        'initiated_by_username': offer.initiated_by.user.username,
        'initiated_reputation': offer.initiated_by.user.reputation_score,
        'acceptances': acceptances,
        'have_cards_available': have_cards_available,
        'want_cards_available': want_cards_available,
        'num_cards_available': len(have_cards_available) + len(want_cards_available),
        'on_detail_page': context.get("request").path.endswith("trades/"+str(offer.pk)+"/"),
    }

@register.inclusion_tag('templatetags/trade_acceptance.html', takes_context=True)
def render_trade_acceptance(context, acceptance):
    """
    Renders a simple trade acceptance view with a single row and simplified header/footer.
    """

    return {
        "acceptance": acceptance,
        "request": context.get("request"),
    }

@register.filter
def get_action_label(acceptance, state_value):
    """
    Calls the acceptance's method to return the alternate action label.
    """
    return acceptance.get_action_label_for_state(state_value)

@register.filter
def action_button_class(state_value):
    """
    Returns daisyUI button classes based on the provided state value.
    """
    mapping = {
        'ACCEPTED': 'btn btn-primary',
        'SENT': 'btn btn-info',
        'RECEIVED': 'btn btn-info',
        'THANKED_BY_INITIATOR': 'btn btn-success',
        'THANKED_BY_ACCEPTOR': 'btn btn-success',
        'THANKED_BY_BOTH': 'btn btn-success',
        'REJECTED_BY_INITIATOR': 'btn btn-error',
        'REJECTED_BY_ACCEPTOR': 'btn btn-error',
    }
    # Return a default style if the state isn't in the mapping.
    return mapping.get(state_value, 'btn btn-outline')

@register.inclusion_tag('templatetags/trade_offer_png.html', takes_context=True)
def render_trade_offer_png(context, offer, show_friend_code=False):
    have_cards_available = offer.have_cards_available
    want_cards_available = offer.want_cards_available

    num_cards = max(len(have_cards_available), len(want_cards_available))
    expanded = (len(have_cards_available) + len(want_cards_available)) > 4
    if expanded:
        num_cards = ceil(num_cards / 2)
    image_height = (num_cards * 40) + 106
                #    cards incl pad + header/footer

    if expanded:
        image_width = (4 * 160) + 110
    else:
        image_width = (2 * 160) + 92

    request = context.get("request")
    if request.get_host().startswith("localhost"):
        base_url = "http://{0}".format(request.get_host())
    else:
        base_url = "https://{0}".format(request.get_host())

    return {
        'offer_pk': offer.pk,
        'offer_hash': offer.hash,
        'rarity_icon': offer.rarity_icon,
        'initiated_by_email': offer.initiated_by.user.email,
        'initiated_by_username': offer.initiated_by.user.username,
        'have_cards_available': have_cards_available,
        'want_cards_available': want_cards_available,
        'in_game_name': offer.initiated_by.in_game_name,
        'friend_code': offer.initiated_by.friend_code,
        'show_friend_code': show_friend_code,
        'num_cards_available': len(have_cards_available) + len(want_cards_available),
        'expanded': expanded,
        'image_width': image_width,
        'image_height': image_height,
        'base_url': base_url,
    }