import requests
import time


def getuserid(accesstoken):
    """ 
        Get the current user's id using the /v1/me endpoint.

        Returns user's id as a string, or None if unable to obtain id.
    """

    headers = {}
    headers["Authorization"] = "Bearer {}".format(accesstoken)

    r = requests.get("https://api.spotify.com/v1/me", headers=headers)
    # print('response = \n\n {} \n\n'.format(r.text))
    # print('userid:\n\n{}'.format(r.json()))


    response = r.json()
    if "id" not in response:
        if response["error"]:
            if response["error"]["status"] == 429:
                # wait for the amount of time specified in response header
                time.sleep(int(r.headers["Retry-After"]) + 1)
                # try again
                return(getuserid(accesstoken))

            else:
                print(response["error"])
                return(None)
        else:
            print('error: getuserid request failed')
            return(None)

    userid = response["id"]
    # print("userid = {}".format(userid))
    return(userid)