#!/usr/bin/env ruby

#######################
# WARNING
# Running this code sample will cost you Browshot credits
#######################

require 'browshot'

browshot = Browshot.new('my_api_key')

screenshot = browshot.screenshot_create('http://www.google.com/', { 'instance_id' => 12, 'size' => 'page' }) # all default parameters, instance_id = 12 (free)
# If the screenshot is already in cache, it could be finished already. Otherwise, wait longer
while (screenshot['status'] != 'finished' && screenshot['status'] != 'error')
  puts "Wait...\n";
  sleep(10)
  screenshot = browshot.screenshot_info(screenshot['id'])
end

# screenshot is done: finished (sucessful) or error (failed)
if (screenshot['status'] == 'error')
  puts "Screenshot failed: #{screenshot['error']}\n" # display the reason for the error
else # request the thumbnail
  image = browshot.screenshot_thumbnail(screenshot['id'])
  
  # save the screenshot
  File.open("browshot.png", 'w') {|f| f.write(image) }
end