import logging

from pyteamsnap.client import TeamSnap

# This retrieves a Python logging instance (or creates it)
logger = logging.getLogger(__name__)


def get_teamsnap_client(request):
    client = request.session.get("teamsnap_client")
    if client:
        logger.info("TeamSnap client found saved in session, loading.")
        return client
    elif not client:
        logger.info("No TeamSnap client saved in session, getting one.")
        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
        )
        client = TeamSnap(token=ts_token)
        request.session["teamsnap_client"] = client
        return client
