import requests


def auth(
    username=None, password=None, apikey=None, refresh_token=None, iam_endpoint=None
):
    """
    Makes a authentication request to the IAM API to retrieve an IAM token and
    IAM Refresh token.

    :param username: Username
    :param password: Password
    :param apikey: IBMCloud/Bluemix API Key
    :param refresh_token: IBM IAM Refresh Token,
        if specified the refresh token is used to authenticate,
        instead of the API key
    :param iam_endpoint: base URL that can be specified
        to override the default IAM endpoint, if one, for example,
        wanted to test against their own IAM or an internal server
    :return: Response
    """
    if not iam_endpoint:
        iam_endpoint = "https://iam.cloud.ibm.com/"

    if iam_endpoint[-1] == "/":
        iam_endpoint = iam_endpoint[:-1]

    api_endpoint = iam_endpoint + "/oidc/token"

    # HTTP Headers
    headers = {"Authorization": "Basic Yng6Yng=", "Accept": "application/json"}

    # HTTP Payload
    data = {
        "response_type": "cloud_iam",
        "uaa_client_id": "cf",
        "uaa_client_secret": "",
    }

    # Setup grant type
    if apikey:
        data["grant_type"] = "urn:ibm:params:oauth:grant-type:apikey"
        data["apikey"] = apikey
    elif refresh_token:
        data["grant_type"] = "refresh_token"
        data["refresh_token"] = refresh_token
    elif username and password:
        data["grant_type"] = "password"
        data["username"] = username
        data["password"] = password
    else:
        raise ValueError(
            "Must specify one of username/password, apikey, or refresh_token!"
        )

    resp = requests.post(api_endpoint, data=data, headers=headers)

    if resp.status_code == 200:
        return resp.json()

    return resp.text