#!/usr/bin/perl -w

use strict;
use warnings;
use Carp;

use WebService::Browshot;

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


my $browshot = WebService::Browshot->new(
	key	=> 'my_api_key',
	debug	=> 0, # no more debug information
);

my $screenshot = $browshot->screenshot_create(url => '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} ne 'finished' &&  $screenshot->{status} ne 'error') {
	print "Wait...\n";
	sleep 10;
	$screenshot = $browshot->screenshot_info(id => $screenshot->{id});
	# or $screenshot = $browshot->screenshot_create(url => 'https://browshot.com/', details => 3, instance => 24, screen_width => 1280, screen_height => 1024);
}

# screenshot is done: finished (sucessful) or error (failed)
if ($screenshot->{status} eq 'error') {
	print "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} != 200) {
		print "The page may not have be reached, HTTP response code was: ", $screenshot->{response_code}, "\n";
	}
	
	# Was it an HTML page, PDF or image?
	if ($screenshot->{content_type} ne 'text/html') {
		print "The page is not HTML, it is ", $screenshot->{content_type}, "\n";
	}
	
	# with details = 3, you can check what asserts were loaded on the page: images, javascript, frames, etc.
	print "There are ", scalar(@{ $screenshot->{images} }), " images on this page:\n";
	foreach my $url (@{ $screenshot->{images} }) {
		print "$url\n";
	}
}
