require LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use HTTP::Cookies;
use HTML::TreeBuilder;
use XML::Atom::SimpleFeed;

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$c = HTTP::Cookies->new(ignore_discard => 1, autosave => 1);
$ua->cookie_jar($c);

($library_card, $pin) = ('00000000000000', '0000');
$action = 'https://ezproxy.torontopubliclibrary.ca/login';
my %data;

my $req = POST $action, [url => 'http://ezproxy.torontopubliclibrary.ca/sso/myacct', user => $library_card, pass => $pin];
my $response = $ua->request($req);


my $feed = XML::Atom::SimpleFeed->new(
    title    => "Library books",
    subtitle => "From the Toronto Public Library",
    link     => "",
    link     => {
	rel  => 'self',
	href => '',
    },
    id       => "",
    author   => "",
    );

if ($response->code == &HTTP::Status::RC_MOVED_PERMANENTLY or
    $response->code == &HTTP::Status::RC_MOVED_TEMPORARILY) {
    # Make a copy of the request and initialize it with the new URI
    my $response = $ua->get($response->header('Location'));
    $response = $ua->get('http://ezproxy.torontopubliclibrary.ca/sso/myacct');

    $p = HTML::TreeBuilder->new_from_content($response->content);
    # Find the Your Account link
    $a = $p->look_down(
	'_tag', 'a',
	sub { $_[0]->as_text =~ m{Your Account} });

    $response = $ua->get('http://catalogue.torontopubliclibrary.ca' . $a->attr('href'));
    $p = HTML::TreeBuilder->new_from_content($response->content);
    @books = $p->look_down(
	'_tag', 'tbody', sub { $_[0]->attr('id') eq 'renewcharge' })->look_down('_tag', 'tr');
    foreach (@books) {
	$t = $_->look_down('_tag', 'a');
	$checkbox = $_->look_down('_tag', 'input');
	if ($t) {
	    my %info;
	    # RENEW^39100049582508^658.84 SWE^1^Sweeney, Susan, 1956-^101 Internet businesses you can start from home : how to choose and build your own successful e-business^
	    if ($checkbox) {
		($command, $info{'id'}, $info{'catno'}, $status, $info{'author'}, $info{'title'}) = split(/\^/, $checkbox->attr('name'));
	    }
	    
	    @tds = $_->look_down('_tag', 'td');
	    $info{'due'} = $tds[3]->as_text;
	    $feed->add_entry(
		title => $info{'title'},
		id => $info{'id'},
		author => $info{'author'},
		summary => $info{'due'},
	    );
	}
    }
}
    
$feed->print;
