#!/usr/bin/env ruby

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

require 'browshot'

browshot = Browshot.new('my_api_key', true) # more debug information


screenshot = browshot.screenshot_create('https://browshot.com/', { 'details' => 3, 'instance' => 24, 'screen_width' => 1280, 'screen_height' => 1024 }) # extra details
# the call to screenshot/create sends the same response as screenshot/information
# so screenshot/create and screenshot/info can be interchanged as long as the cache value is long enough
while (screenshot['status'] != 'finished' && screenshot['status'] != 'error')
  puts "Wait...\n"
  sleep(10)
  screenshot = browshot.screenshot_info(screenshot['id'], { 'details' => 3 })
  # or $screenshot = $browshot->screenshot_create(array('url' => 'https://browshot.com/', 'details' => 3, 'instance' => 24, 'screen_width' => 1280, 'screen_height' => 1024));
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

  # If you call $browshot->screenshot_create with the same parameters, a new screenshot will be requested.
else # screenshot is finished
  # did the page load (200 OK) or was mnissing (404 Not Found) or some error (40X, 50X);
  if (screenshot['response_code'].to_i != 200)
    puts "The page may not have be reached, HTTP response code was: #{screenshot['response_code']}\n"
  end
  
  # Was it an HTML page, PDF or image?
  if (screenshot['content_type'] != 'text/html')
    puts "The page is not HTML, it is #{screenshot['content_type']}\n"
  end
  
  # with details = 3, you can check what asserts were loaded on the page: images, javascript, frames, etc.
  if (screenshot.key?('images') && screenshot['images'].kind_of?(Array))
    puts "There are #{screenshot['images'].count} images on this page:\n"
    
    screenshot['images'].each { |url|
      puts "#{url}\n"
    }
  end
end