import requests
import logging
import time
import json


def callRaceMonitor(endpoint, payload):
    """
    Function name: callRaceMonitor
    Arguments: endpoint, payload
    Description: Take a race monitor API endoint (https://www.race-monitor.com/APIDocs)
    and payload, and request the object from the API. Handles rate limiting with sleep.
    """
    api_base_url = 'https://api.race-monitor.com'
    api_endpoint = endpoint
    api_url = api_base_url + api_endpoint
    r = requests.post(api_url, data = payload)

    while r.status_code == 429:
        logging.error('{} - Too many requests, waiting 10 seconds...'.format(r.status_code))
        time.sleep(10)
        r = requests.post(api_url, data = payload)
    
    if r.status_code == 200:
        return json.loads(r.text)
    else:
        logging.error('Error {}'.format(r.status_code))
    return