from gi.repository import GLib, Soup

# Hypothesis: downloading considerably big file with soup blocks main loop

# The file for demostration is an Image of size 1.3MB hosted at
# http://peach.blender.org/wp-content/uploads/big_big_buck_bunny.jpg


ctx = GLib.MainContext.default()
loop = GLib.MainLoop.new(ctx, False)

# We will try confirming the issue this way: we will put current time (as
# reported by get_monotonic_time) every 100 milliseconds into the list and
# and after the file is downloaded check whether spacing between the times
# stored in our list are consistent (up to some sane error, of course)
#
# It times are not consistent, the main loop was obviously blocked at some
# point

timings = []
def add_time_to_list(*args):
    t = GLib.get_monotonic_time()
    timings.append(t)
    return True
GLib.timeout_add(100, add_time_to_list, None)


session = Soup.Session.new()
url = 'http://peach.blender.org/wp-content/uploads/big_big_buck_bunny.jpg'
message = Soup.Message.new('GET', url)
start = None

def image_fetched(session, message, data):
    end = GLib.get_monotonic_time()
    print('fetched image at', end)
    print('time for image to download', (end - start) / 1000.0)
    timings.append(end)
    print('differences between timings (in ms, should be as close to ' +
          '100 as possible)')
    last_timing = timings[0]
    for timing in timings[1:]:
        print((timing - last_timing) / 1000.0)
        last_timing = timing
    loop.quit()

def start_download(*args):
    global start
    start = GLib.get_monotonic_time()
    print('fetching image at', start)
    session.queue_message(message, image_fetched, None)
    return False

# We'll only start a download after 300ms in order for some timings to
# be collected
GLib.timeout_add(300, start_download, None)

loop.run()
print('finished main loop')
