"""
Misc functions that are useful when scraping webpages
"""
import time
import random


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def random_sleep(lower_limit, upper_limit):
    """
    Sleep for a random amount of time between the lower limit and the upper
    limit

    Parameters
    ----------

    lower_limit :`float`
        The lower limit to sleep forma
    upper_limit :`float`
        The upper limit to sleep for

    Returns
    -------

    sleep_time :`float`
        The duration of the sleep
    """

    sleep_time = random.uniform(float(lower_limit), float(upper_limit))

    # Perform the random sleep betwen both values
    time.sleep(sleep_time)

    return sleep_time


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def test_request_response(response):
    """
    Tests the response from an web request and give an error if it is not in
    the 200 range

    Parameters
    ----------

    response : :obj:`response`
        A requests response from a get

    Raises
    ------

    RuntimeError
        If the response does not start with 2
    """

    # If it does nto satrtwith 2 then error out
    if not str(response.status_code).startswith("2"):
        raise RuntimeError("Error status_code of '{0}'".format(
            response.status_code))
