from django.shortcuts import render

from teamsnap.models import Opponent, Team
from teamsnap.utils import get_teamsnap_client


def gamecard(request, team_id, event_id):
    import re

    from pyteamsnap.api import (
        Availability,
        AvailabilitySummary,
        Event,
        EventLineup,
        EventLineupEntry,
        Member,
    )

    client = get_teamsnap_client(request)
    ts_bulkload = client.bulk_load(
        team_id=team_id,
        types=[Event, EventLineup, EventLineupEntry, AvailabilitySummary, Member],
        event__id=event_id,
    )

    ts_event = [
        i for i in ts_bulkload if isinstance(i, Event) and i.data["id"] == event_id
    ][0]
    ts_availabilities = Availability.search(client, event_id=ts_event.data["id"])

    ts_lineup_entries = EventLineupEntry.search(client, event_id=event_id)

    if ts_lineup_entries:
        # ts_lineup = EventLineup.get(
        #     client, id=ts_lineup_entries[0].data["event_lineup_id"]
        # )
        pass
    else:
        # ts_lineup = EventLineup.search(client, event_id=event_id)
        pass

    ts_members = [i for i in ts_bulkload if isinstance(i, Member)]
    # ts_member_lookup = {m.data["id"]: m for m in ts_members}
    ts_availability_lookup = {m.data["member_id"]: m for m in ts_availabilities}
    ts_lineup_entries_lookup = {m.data["member_id"]: m for m in ts_lineup_entries}

    members = []

    for member in ts_members:
        if not member.data["is_non_player"]:
            members.append(
                {
                    "member": getattr(member, "data"),
                    "availability": getattr(
                        ts_availability_lookup.get(member.data["id"], {}), "data", {}
                    ),
                    "lineup_entry": getattr(
                        ts_lineup_entries_lookup.get(member.data["id"], {}), "data", {}
                    ),
                }
            )

    members = sorted(
        members,
        key=lambda d: (
            {None: 3, 0: 2, 2: 1, 1: 0}.get(  # No Response  # No  # Maybe  # Yes
                d["availability"].get("status_code")
            ),
            d["member"].get("last_name"),
        ),
    )

    members_startinglineup = []
    members_startingpositiononly = []

    for member in members:
        if re.search(
            r"([A-Z0-9]+)(?:\s+\[(.*)\])?", member["lineup_entry"].get("label", "")
        ):
            position, position_note = re.search(
                r"([A-Z0-9]+)(?:\s+\[(.*)\])?", member["lineup_entry"].get("label", "")
            ).groups()
        else:
            position, position_note = ("", "")

        position_only = position_note == "PO"

        if position_only:
            member["lineup_entry"]["label"] = position

        if member["lineup_entry"].get("id") and not position_only:
            members_startinglineup.append(member)
        elif member["lineup_entry"].get("id") and position_only:
            members_startingpositiononly.append(member)

    members_startinglineup = sorted(
        members_startinglineup,
        key=lambda d: d.get("lineup_entry", {}).get("sequence", 100),
    )

    context = {
        "event": ts_event,
        "members": members,
        "members_startinglineup": members_startinglineup,
        "members_startingpositiononly": members_startingpositiononly,
        "ts_team": Team.objects.get(id=team_id),
        "ts_opponent": Opponent.objects.get(id=ts_event.data["opponent_id"]),
    }
    return render(request, "gamecard/gamecard.html", context=context)
