import requests
import logging


def dockerhub_get_session(secret_dict):
    """Gets a session to the DockerHub User API from a secret dictionary

    This helper function tries to connect to the DockerHub User API by grabbing login info
    from the secret dictionary. If successful, it returns the http session, else None

    Args:
        secret_dict (dict): The Secret Dictionary

    Returns:
        Session: The requests.Session object if successful. None otherwise

    Raises:
        KeyError: If the secret json does not contain the expected keys

    """
    # Log in
    session = requests.Session()
    logging.info('Logging in with provided credentials...')
    url = "https://id.docker.com/api/id/v1/user/login"
    json = {"password": secret_dict['password'], "username": secret_dict['username']}
    r = session.post(url, json=json)

    if r.status_code != 200:
        logging.error("Login Failed. Error: {}".format(r.status_code))
        return None

    # Get CSRF Token
    logging.info('Getting CSRF Token...')
    url = "https://cloud.docker.com/sso/start"
    r = session.get(url)

    if r.status_code != 200 or not session.cookies['csrftoken']:
        logging.error('CSRFToken acquisition failed')
        return None

    logging.info('Successfully logged in to DockerHub')

    return session