#!/usr/bin/perl -w
use strict;
use POE;
use POE::Component::Client::UserAgent;

# URL is first parameter
my($url) = shift;
defined($url) or die("usage: test-ua URL [debuglevel]\n");
print ("Retrieving: $url\n");

# more debugging stuff
my $debuglevel = shift || 0;
POE::Component::Client::UserAgent::debug $debuglevel;

# create client session
POE::Session -> create (
			inline_states => {
			   _start => \&_start,
			   response => \&response
		           },
			);

# now run POE!
$poe_kernel -> run;

# this is the first event to arrive
sub _start
{
    # create the PoCoCl::UserAgent session
    POE::Component::Client::UserAgent -> new(timeout => 5);

    # hand it our request
    $_[KERNEL] -> post (
			# default alias is 'useragent'
			useragent => 'request',
			{
			    # request some non-existant file
			    request => HTTP::Request -> new(GET => $url),
			    # let UserAgent know where to deliver the response
			    response => $_[SESSION] -> postback ('response')
			}
		       );
    # Once we are done posting requests, we can post a shutdown event
    # to the PoCoCl::UserAgent session. Responses will still be returned
    $_[KERNEL] -> post (useragent => 'shutdown');
}

# Here is where the response arrives. Actually in this example we
# would get more than one response, as hotmail home page is a mere
# redirect to some address at passport.com. The component processes
# the redirect automatically by default.
sub response
{
    # @{$_[ARG0]} is the list we passed to postback()
    # after the event name, empty in this example
    # @{$_[ARG1]} is the list PoCoCl::UserAgent is passing back to us
    my ($request, $response, $entry) = @{$_[ARG1]};
    print "Successful response arrived!\n"
          if $response -> is_success;
    print "PoCoCl::UserAgent is automatically redirecting the request\n"
          if $response -> is_redirect;
    print "The request failed. " . $response->status_line ."\n"
          if $response -> is_error;
}




