use strict;
use warnings;

use CGI;
use Encode;
use LWP::Simple;
use XML::Simple;
use Data::Dumper;

my $aws_access_key_id = '1DGPW2R0MMDD02R3PBR2';
my $associate_tag = 'kazstudi-22';

# Output files.
my $file_response = 'amazon_response.xml';
my $file_xml = 'amazon_xml.xml';
my $file_dumper = 'amazon_dumper.txt';

# Set up keywords.
my $encoding = 'Shift_JIS';
my $raw_keywords = "結城浩";
my $keywords = CGI::escape(Encode::decode($encoding, $raw_keywords));

# Set up URL.
my $request_url = 'http://webservices.amazon.co.jp/onca/xml';
my @option_list = (
    "Service=AWSECommerceService",
    "AWSAccessKeyId=${aws_access_key_id}",
    "Operation=ItemSearch",
    "Keywords=${keywords}",
    "SearchIndex=Books",
    "ResponseGroup=Request,Small,Images",
    "AssociateTag=${associate_tag}",
    "Version=2007-01-15",
);

# Assemble all options.
my $option_string = join('&', @option_list);
my $url = "${request_url}?${option_string}";

# Retrieve result.
print STDERR "\$url = ${url}\n";
my $response_string = get($url);
my $response_hashref = XMLin(\$response_string);
my $xml_string = XMLout($response_hashref);
utf8::encode($xml_string); # UTF-8 flag OFF
my $dumped = Dumper($response_hashref);

# Print as string.
print "$file_response\n";
open(RESPONSE, "> $file_response") or die;
print RESPONSE $response_string;
close(RESPONSE);

# Print as XML.
print "$file_xml\n";
open(XML, "> $file_xml") or die;
print XML $xml_string;
close(XML);

# Print as Dumped.
print "$file_dumper\n";
open(DUMPER, "> $file_dumper") or die;
print DUMPER $dumped;
close(DUMPER);
