import datetime

from django.shortcuts import redirect, render

from teamsnap.views import get_teamsnap_client


def dashboard(request, team_id=None):
    if not team_id:
        return redirect(
            "teamsnap_dashboard", team_id=request.user.preferences.managed_team_id
        )

    from pyteamsnap.api import AvailabilitySummary, Event

    client = get_teamsnap_client(request)
    ts_events = Event.search(client, team_id=team_id)
    ts_availability_summaries_d = {
        a.data["id"]: a for a in AvailabilitySummary.search(client, team_id=team_id)
    }
    ts_events_future = [
        e
        for e in ts_events
        if e.data["start_date"] > datetime.datetime.now(datetime.timezone.utc)
    ]
    ts_events_past = [
        e
        for e in reversed(ts_events)
        if e.data["start_date"] < datetime.datetime.now(datetime.timezone.utc)
    ]

    return render(
        request,
        "dashboard.html",
        {
            "ts_events_future": ts_events_future,
            "ts_events_past": ts_events_past,
            "events_availabilities": [
                (e, ts_availability_summaries_d[e.data["id"]]) for e in ts_events_future
            ],
        },
    )
