from django.shortcuts import render

import gamechanger.models as GcModels
from gamechanger.utils.gamechanger import get_gamechanger_client
from teamsnap.models import Opponent, Team
from teamsnap.utils import get_teamsnap_client


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

    from pyteamsnap.objects 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],
    )

    ts_events = [e for e in ts_bulkload if isinstance(e, Event)]
    ts_events.sort(key=lambda d: d.data.get("start_date"))
    ts_event = [e for e in ts_events if e.data["id"] == event_id][0]
    ts_events_future = ts_events[ts_events.index(ts_event) + 1 :]
    ts_events_past = ts_events[: ts_events.index(ts_event)]

    ts_availabilities = Availability.search(client, team_id=team_id)

    ts_availabilities_future = list(
        filter(
            lambda a: a.data["event_id"] in [e.data["id"] for e in ts_events_future],
            ts_availabilities,
        )
    )
    ts_availabilities_past = list(
        filter(
            lambda a: a.data["event_id"] in [e.data["id"] for e in ts_events_past],
            ts_availabilities,
        )
    )

    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["id"]: m for m in ts_availabilities}
    ts_lineup_entries_lookup = {m.data["member_id"]: m for m in ts_lineup_entries}

    gc_client = get_gamechanger_client(request)
    stats = gc_client.get_stats()
    stats_lookup = {
        GcModels.Player.objects.filter(id=k).first().teamsnap_member_id: stat_row
        for k, stat_row in stats.items()
    }

    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(
                            f"{member.data['id']}-{event_id}", {}
                        ),
                        "data",
                        {},
                    ),
                    "lineup_entry": getattr(
                        ts_lineup_entries_lookup.get(member.data["id"], {}), "data", {}
                    ),
                    "availability_future": list(
                        filter(
                            lambda a: a.data.get("member_id") == member.data["id"],
                            ts_availabilities_future,
                        )
                    )[:4],
                    "availability_past": list(
                        filter(
                            lambda a: a.data.get("member_id") == member.data["id"],
                            ts_availabilities_past,
                        )
                    )[:4],
                    "stats": stats_lookup.get(member.data["id"]),
                }
            )

    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 = []
    members_bench = []

    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:
            member["in_starting_lineup"] = True
            members_startinglineup.append(member)
        elif member["lineup_entry"].get("id") and position_only:
            member["in_starting_lineup"] = False
            members_startingpositiononly.append(member)
        elif member["availability"]["status_code"] in [1, 2]:
            member["in_starting_lineup"] = False
            members_bench.append(member)

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

    context = {
        "event": ts_event,
        "events_future": ts_events_future[:4],
        "events_past": list(reversed(ts_events_past))[:4],
        "members": members,
        "members_startinglineup": members_startinglineup,
        "members_startingpositiononly": members_startingpositiononly,
        "members_bench": members_bench,
        "blankrows_lineup": range(
            13 - len(members_startingpositiononly) - len(members_bench)
        ),
        "ts_team": Team.objects.get(id=team_id),
        "ts_opponent": Opponent.objects.filter(id=ts_event.data["opponent_id"]).first,
        "blankrows_info": range(25 - len(members)),
    }
    return render(request, "gamecard/gamecard.html", context=context)
