from zoneinfo import ZoneInfo

from django.http import HttpResponse
from django.shortcuts import redirect, render


# Create your views here.
def image_generator(request, team_id, event_id):
    request.user.socialaccount_set.filter(provider="teamsnap").first()
    current_teamsnap_user = request.user.socialaccount_set.filter(
        provider="teamsnap"
    ).first()

    TOKEN = current_teamsnap_user.socialtoken_set.order_by("-expires_at").first().token

    from pyteamsnap.client import TeamSnap
    from pyteamsnap.objects import Event

    client = TeamSnap(token=TOKEN)

    ts_event = Event.get(client, id=event_id)
    return render(request, "instagen/instagen.html", context={"event": ts_event})


def get_matchup_image(request, team_id, event_id, dimensions=None, background=None):
    import io

    from pyteamsnap.objects import Location, Opponent, Team

    from .utils.gen_image import Location as ImagegenLocation
    from .utils.gen_image import Team as ImagegenTeam
    from .utils.gen_image import gen_image, gen_results_image

    if not team_id:
        return redirect(
            "teamsnap_event", team_id=request.user.preferences.managed_team_id
        )
    request.user.socialaccount_set.filter(provider="teamsnap").first()
    current_teamsnap_user = request.user.socialaccount_set.filter(
        provider="teamsnap"
    ).first()

    ts_token = (
        current_teamsnap_user.socialtoken_set.order_by("-expires_at").first().token
    )

    from pyteamsnap.client import TeamSnap
    from pyteamsnap.objects import Event

    teamsnap = TeamSnap(token=ts_token)

    if request.GET:
        BACKGROUND = request.GET.get("background", "location")
        game_id = event_id
        dimensions = request.GET.get("dimensions")
        width = int(dimensions.split("x")[0])
        height = int(dimensions.split("x")[1])

        ts_event = Event.get(teamsnap, game_id).data
        fave_team = Team.get(teamsnap, ts_event["team_id"]).data
        opponent_team = Opponent.get(teamsnap, ts_event["opponent_id"]).data
        location = Location.get(teamsnap, ts_event["location_id"]).data
        formatted_results = ts_event["formatted_results"]
        if formatted_results:
            # L 4-3
            runs_for = formatted_results.split(" ")[1].split("-")[0]
            runs_against = formatted_results.split(" ")[1].split("-")[1]
        else:
            runs_for, runs_against = None, None

        logo_image_directory = "instagen/static/instagen/logos-bw/{filename}.{ext}"
        venue_image_directory = "instagen/static/instagen/locations/{filename}.{ext}"

        def shortname_from_name(name):
            return name.replace(" ", "").lower()

        # date = parser.parse(ts_event['start_date'])
        # date = date.astimezone(ZoneInfo("America/Chicago"))
        game_info = {
            "date": ts_event["start_date"].astimezone(
                ZoneInfo(ts_event["time_zone_iana_name"])
            ),
            "team_fave": ImagegenTeam(
                name=fave_team["name"],
                image_directory=logo_image_directory.format(
                    filename=shortname_from_name(fave_team["name"]), ext="png"
                ),
            ),
            "team_opponent": ImagegenTeam(
                name=opponent_team["name"],
                image_directory=logo_image_directory.format(
                    filename=shortname_from_name(opponent_team["name"]), ext="png"
                ),
            ),
            "location": ImagegenLocation(
                name=location["name"],
                image_directory=venue_image_directory.format(
                    filename=shortname_from_name(location["name"]), ext="png"
                ),
                # address=location['address']
            ),
            "runs_for": runs_for,
            "runs_against": runs_against,
        }

        if not game_info["runs_for"] and not game_info["runs_against"]:
            image = gen_image(
                **game_info, background=BACKGROUND, width=width, height=height
            )
        elif game_info["runs_for"] and game_info["runs_against"]:
            image = gen_results_image(
                **game_info, background=BACKGROUND, width=width, height=height
            )
        else:
            raise Exception

        imgByteArr = io.BytesIO()
        image.save(imgByteArr, format="PNG")
        imgByteArr = imgByteArr.getvalue()

        return HttpResponse(imgByteArr, content_type="image/png")
