import time
import requests
import uuid
import webbrowser


def _check_for_api(launch_browser=False, timeout=5):
    """Helper method to check for the API to be live for up to 15 seconds and then optionally launch a browser window

    Args:
        launch_browser(bool): flag indicating if the browser should be launched on success == True
        timeout(int): Number of seconds to wait for the API before returning
    Returns:
        bool: flag indicating if the API is ready
    """
    time.sleep(1)
    success = False
    for _ in range(timeout):
        try:
            resp = requests.get("http://localhost:10000/api/ping?v={}".format(uuid.uuid4().hex))

            if resp.status_code == 200:
                success = True
                break
        except requests.exceptions.ConnectionError:
            # allow connection errors, which mean the API isn't up yet.
            pass

        # Sleep for 1 sec and increment counter
        time.sleep(1)

    if success is True and launch_browser is True:
        time.sleep(2)
        # If here, things look OK. Start browser
        webbrowser.open_new("http://localhost:10000")

    return success