#!/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	=> 1, # print more debug information
);

my $list = $browshot->screenshot_multiple(
	urls => ['http://www.google.com/', 'https://browshot.com/', 'http://mobilito.net/'], # up to 5 URLs
	instances => [12, 24, 72], # up to 10
	size => 'page', # all options of screenshot/create are valid
);


my @ids = (); # will hold all screenshot IDs

foreach my $id (keys %$list) {
	push(@ids, $id);
}

sleep 20;


while (scalar @ids > 0) { # go through each screenshot
	my $i = 0;
	while ($i < scalar @ids) {
		my $id = $ids[$i];

		my $info = $browshot->screenshot_info(id => $id);
		if ($info->{status} eq 'finished') {
			$browshot->screenshot_thumbnail_file(id => $id, file => "$id.png");
			splice(@ids, $i, 1); # remove ID from the list
		}
		elsif ($info->{status} eq 'error') {
			print "Screenshot failed: ", $info->{error}, "\n";
			print "\tURL: ", $info->{url}, "\n";
			print "\tinstance_id: ", $info->{instance_id}, "\n";
			print "\n";
			
			splice(@ids, $i, 1); # remove ID from the list
		}
		else {
			# wait
			$i++;
		}
	}
	
	sleep 10 if (scalar @ids > 0);
}