import json
import requests


def get_onboard_certificates(clearpass_fqdn, access_token, username):
    """Get all valid certificates (not revoked or expired) for user"""

    url = "https://{}/api/certificate".format(clearpass_fqdn)

    queryfilter = {'mdps_user_name': username, 'is_valid':'true'}
    payload = {'filter':json.dumps(queryfilter),'calculate_count':'true'}

    headers = {'Authorization':'Bearer {}'.format(access_token), "Content-Type": "application/json"}

    try:
        r = requests.get(url, headers=headers, params=payload)
        r.raise_for_status()
        json_response = r.json()
    except Exception as e:
        print(e)
        exit(1)

    certs = [(i['id'], i['ca_id']) for i in json_response['_embedded']['items']]

    return certs