#!/usr/bin/perl
###########################################
# reviews
# Mike Schilli, 2003 (m@perlmeister.com)
###########################################
use warnings;
use strict;

use Net::Amazon;
use Net::Amazon::Attribute::Review;
use Text::Wrap;

#use Log::Log4perl qw(:easy);
#Log::Log4perl->easy_init({level => $DEBUG, layout => '%F{1}-%L: %m%n'});

my $ua = Net::Amazon->new(
    token       => $ENV{AMAZON_TOKEN},
    secret_key  => $ENV{AMAZON_SECRET_KEY},
);

my $resp = $ua->search(
    asin  => ($ARGV[0] || "0471237124"),
);

die "Request failed" unless $resp->is_success();

for my $property ($resp->properties()) {

    my $count = 0;
    print "Reviews for '", $property->title(), "'\n\n";

    my $reviewset = $property->review_set();

    print "Average Rating:    ", $reviewset->average_customer_rating(), "\n";
    print "Total Reviews:     ", $reviewset->total_reviews(), "\n\n";

    for my $review ($reviewset->reviews()) {
      print "=== Review #", ++$count, " ===\n";
      print shape("Rating:            ", $review->rating()), "\n";
      print shape("Summary:           ", $review->summary()), "\n";
      print shape("Comment:           ", $review->comment()), "\n";
      print "\n";
    }
}

#######################################
sub shape {
#######################################
    my($header, $text) = @_;

    my $result = join '', 
               fill($header, " " x length($header), split /\n/, $text);

    return $result;
}
