#!/mit/perl5/bin/perl -wT

use lib "/mit/marthag/lib/site_perl/5.6.0/";
use lib "/mit/marthag/share/site_perl/5.6.0";
use lib "/mit/marthag/share/perl5.6.0/";
use lib "/mit/marthag/lib/perl5/site_perl/5.6.1";
use lib "/mit/marthag/lib/perl5/5.6.1/sun4-solaris/";

use Net::Amazon;
# use Log::Log4perl qw(:easy);
# Log::Log4perl->easy_init($DEBUG);

 use Palm::PDB;
    use Palm::ListDB;
   my $pdb = new Palm::ListDB;
    $pdb->{name} = 'US Books';
    $pdb->{appinfo}{writeProtect} = 1;		# *ListDb's* write   protection
    $pdb->{appinfo}{field1} = 'Authors';
    $pdb->{appinfo}{field2} = 'Title';
    $pdb->addCategory('Book');



while ($isbn = <STDIN>) {
chomp($isbn);

my $ua = Net::Amazon->new(
   token       => 'D2DF0COTRJFEAC'
   ) ;


# search amazon us  for the book
my $response = $ua->search(asin => $isbn);
#my $req = Net::Amazon::Request::ASIN->new( 
#		   asin  => $isbn,
##		   locale => 'uk',
#		   type  => 'lite'
#				   );
#my $us_resp = $ua->request($req);
#if ($us_resp->is_success()) {
#  print $us_resp->as_string()."\n";

if($response->is_success()) {
      print $response->as_string(), "\n";

#for my $prop ($us_resp->properties) {
for my $prop ($response->properties) {
    $author = commify_series($prop->authors()),
    $title = $prop->title();
}
	my $record = $pdb->new_Record( category => 'Book',
	       field1   => $author,
	       field2   => $title,
               note    => $isbn );
	$pdb->append_Record($record);	


} else {
#      print "Error: ", $us_resp->message(), "\n";
      print "Error: ", $response->message(), "\n";
  }

}

$pdb->Write("US_Books.pdb");


sub commify_series {
    # from the Perl Cookbook

    (@_ == 0) ? '' :
    (@_ == 1) ? $_[0]   :
    (@_ == 2) ? join(" and ", @_) :
            join(", ", @_[0 .. ($#_-1)], "and $_[1]");

	    }
