#!/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 (#{screenshot['status']})...\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

# you can combine several calls into 1: screenshot_create + screenshot_host
screenshot = browshot.screenshot_create('https://browshot.com/',
{
	'instance_id' => 24, # premium
	'screen_width' => 1600, # wide screen
	'screen_height' => 1200, 
	'size' => 'page', # full page
	'delay' => 25, # greater delay if the page si very longer
	'hosting' => 's3', # make sure you have set up your S3 bucket with the right ACL
	'hosting_bucket' => 'my_bucket',
	'hosting_file' => 'myfile.png', # can be omitted
	'hosting_width' => 400, # thumbnail 400px wide
})


# Make multiple screenshots of the same page (loaded once)
screenshot = browshot.screenshot_create('https://youtube.com/',
{
	'instance_id' => 24, # premium
	'shots' => 5 ,          # 5 screenshots
	'shot_interval' => 10, # every 10 seconds
	'screen_width' => 1280,
	'screen_height' => 1024,
})

sleep(60)

screenshot = browshot.screenshot_info(screenshot['id'])
if (screenshot['status'] == 'finished')
  # download the 5 screenshots
  for i in 1..5
    browshot.screenshot_thumbnail_file(screenshot['id'], "#{i}.png" , { 'height' => 600, 'shot' => i })
   end
end


# Host the screenshot on S3
screenshot = browshot.screenshot_create('https://youtube.com/',
{
	'instance_id' => 24, # premium
	'screen_width' => 1280,
	'screen_height' => 1024,
	'hosting' => 's3',
	'hosting_bucket' => 'my_bucket',
	'hosting_file' => 'youtube.png',
	'hosting_width' => 600 # thumbnail
})

sleep(60)

screenshot = browshot.screenshot_info(screenshot['id'])
if (screenshot['status'] == 'finished')
  # The screenshot may not be hosted yet
  if (screenshot.key?('hosted_url') && screenshot['hosted_url'] != '')
    puts "\nScreenshot hosted at #{screenshot['hosted_url']}\n"
  end
end
