import time
import requests
import uuid
import webbrowser


def _check_for_api(port: int = 10000, launch_browser: bool = False, timeout: int = 5):
    """Check for the API to be live for up to `timeout` seconds, then optionally launch a browser window

    Args:
        port(int): port the server is running on
        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
    """
    protocol = "http"
    if port == 443:
        protocol = "https"

    success = False
    for _ in range(timeout):
        time.sleep(1)
        try:
            resp = requests.get("{}://localhost:{}/api/ping?v={}".format(protocol, port, uuid.uuid4().hex),
                                verify=False)

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

    if success is True and launch_browser is True:
        time.sleep(1)
        # If here, things look OK. Start browser
        webbrowser.open_new("{}://localhost:{}".format(protocol, port))

    return success