#!/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 => '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} ne 'finished' &&  $screenshot->{status} ne 'error') {
	print "Wait...\n";
	sleep 10;
	$screenshot = $browshot->screenshot_info(id => $screenshot->{id});
}

# 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
}
else { # request the thumbnail
	my $image = $browshot->screenshot_thumbnail(id => $screenshot->{id});
	
	# save the screenshot
	open PNG, "> browshot.png" or croak "Cannot open browshot.png: $!\n";
	binmode PNG;
	print PNG $image;
	close PNG;
}


# you can combine several calls into 1: screenshot_create + screenshot_host
$screenshot = $browshot->screenshot_create(
	url 			=> '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(
	url 			=> '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(id => $screenshot->{id});
if ($screenshot->{status} eq 'finished') {
	# download the 5 screenshots
	for (my $i = 1; $i <= 5; $i++) {
		$browshot->screenshot_thumbnail_file(id => $screenshot->{id}, height => 600, shot => $i, file => "$i.png");
	}
}


# Host the screenshot on S3
$screenshot = $browshot->screenshot_create(
	url => '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(id => $screenshot->{id});
if ($screenshot->{status} eq 'finished') {
	# The screenshot may not be hosted yet
	if (exists($screenshot->{hosted_url}) && $screenshot->{hosted_url} ne '') {
		print "\nScreenshot hosted at ", $screenshot->{hosted_url}, "\n";
	}
}