#!/usr/bin/perl -w

# 2007-10-13 Hisaaki SHIBATA <shibata@luky.org>

# This program shows how to use LWP::Simple to make an Amazon Web
# Services (AWS) REST request, and how to process the response with
# XML::XPath.

use strict;
use LWP::Simple qw($ua);

use MT::Template::Context;
use XML::XPath;
use Encode;
use DB_File;
use Fcntl;

MT::Template::Context->add_tag( Rest => \&rest );

# Retrieve command line arguments and combine them 
# with escaped space characters.

sub rest {
    my $ctx    = shift;
    my $args   = shift;
    my $itemid = $args->{asin};
    my %rdat = ();
    my $xp   = localtime() . " Cache-hit ";
    my $CACHE_DIR ||= "/var/www/archives/cache";

    # Cache check
    if ( -s "$CACHE_DIR/$itemid" ) {
        open( LOG, ">> $CACHE_DIR/log" );
        print LOG $xp, $itemid, "\n\n";
        close(LOG);
    }
    else {

        # Send the request using HTTP GET. &  Process XML response with XPath.
        $xp = setdcache($itemid);
    }
    tie %rdat, "DB_File", "$CACHE_DIR/$itemid", O_RDONLY, 0644, $DB_HASH;

    #    tie %rdat, "DB_File", "$CACHE_DIR/$itemid", O_RDWR, 0644, $DB_HASH;
    #    $rdat{title}       = encode( "euc-jp", $rdat{title} );
    #    $rdat{author}      = encode( "euc-jp", $rdat{author} );
    #    $rdat{artist}      = encode( "euc-jp", $rdat{artist} );
    #    $rdat{manufacture} = encode( "euc-jp", $rdat{manufacture} );
    #    $rdat{price}       = encode( "euc-jp", $rdat{price} );
    my $image = $rdat{medium_img};
    if ( defined( $args->{img} ) ) { $image = $args->{img}; }
    return <<EOT;
<div id=awsasin>
<table width="90%">
<tr>
 <td> <a href="$rdat{url}">
  <img src="$image" border="0" alt="$rdat{title}">
  </a>
 </td>
 <td>
  ¡ÚÂêÌ¾¡Û<a href="$rdat{url}"><strong>$rdat{title}</strong></a><br>
  ¡Úºî¼Ô¡Û$rdat{author}$rdat{artist}<br>
  ¡ÚÀ©ºî¡Û$rdat{manufacture}   ¡Ú²Á³Ê¡Û$rdat{price}<br>
  ¡ÚÈ¯Çä¡Û$rdat{release} ¡ÚASIN¡Û$rdat{asin}  ¡Ú¥Ç¡¼¥¿¼èÆÀÆü¡Û$rdat{getdate}<br>
 </td>
</tr>
<tr> </tr>
</table>
</div>
EOT
    untie %rdat;
}

sub setdcache() {

    my $itemid = shift;
    my %rdat   = ();

    # Define parts of the REST request.
    my $baseurl       = "http://xml-jp.amznxslt.com/onca/xml";
    my $service       = "AWSECommerceService";
    my $associatetag  = "htthooeuqorg-22";
    my $accesskey     = "10FAEQBSPK8MF53W0VG2";
    my $operation     = "ItemLookup";
    my $idtype        = "ASIN";
    my $contenttype   = "text/xml";
    my $page          = "1";
    my $responsegroup = "ItemIds,ItemAttributes,Images,Offers";
    my $version       = "2006-03-08";

    my $CACHE_DIR ||= "/var/www/archives/cache";

    # Assemble the REST request URL.
    my $request = "$baseurl?"
      . "Service=$service&"
      . "AssociateTag=$associatetag&"
      . "AWSAccessKeyId=$accesskey&"
      . "Operation=$operation&"
      . "IdType=$idtype&"
      . "ItemId=$itemid&"
      . "ContentType=$contenttype&"
      . "Page=$page&"
      . "ResponseGroup=$responsegroup&"
      . "Version=$version";

    # Send the request using HTTP GET.
    my $ua = new LWP::UserAgent;
    $ua->timeout(60);
    my $response = LWP::Simple::get($request);

    # Process XML response with XPath.
    my $xp = XML::XPath->new( xml => $response );

    if ( $xp->find("//Error") ) {
        print "There was an error processing your request:\n", "  Error code: ",
          $xp->findvalue("//Error/Code"), "\n", "  ",
          $xp->findvalue("//Error/Message"), "\n\n";
        open( LOG, ">> $CACHE_DIR/log" );
        $rdat{getdate} = localtime();
        print LOG $rdat{getdate}, "Error ", $xp, $itemid, $request, "\n\n";
        close(LOG);
        return $xp;
    }
    else {
        tie %rdat, "DB_File", "$CACHE_DIR/$itemid", O_RDWR | O_CREAT, 0644,
          $DB_HASH;
        $rdat{title} = encode( "euc-jp", $xp->findvalue("//Title") );
        $rdat{keyphrases} =
          encode( "euc-jp", $xp->findvalue("//ProductGroup") );
        $rdat{features} =
          encode( "euc-jp", $xp->findvalue("//ItemAttributes/Format") );
        $rdat{medium_img} = $xp->findvalue("//Item/MediumImage/URL");
        $rdat{large_img}  = $xp->findvalue("//Item/LargeImage/URL");
        $rdat{small_img}  = $xp->findvalue("//Item/SmallImage/URL");
        $rdat{url}        = $xp->findvalue("//DetailPageURL");
        $rdat{author}     = encode( "euc-jp", $xp->findvalue("//Author") );
        $rdat{artist} =
          encode( "euc-jp",
            $xp->findvalue("//Artist") . $xp->findvalue("//Actor") );
        $rdat{manufacture} =
          encode( "euc-jp", $xp->findvalue("//Manufacturer") );
        $rdat{distributor} = $rdat{manufacture};
        $rdat{price}   = encode( "euc-jp", $xp->findvalue("//FormattedPrice") );
        $rdat{release} = encode( "euc-jp",
                $xp->findvalue("//ReleaseDate")
              . $xp->findvalue("//PublicationDate") );
        $rdat{asin}    = $xp->findvalue("//ASIN");
        $rdat{media}   = encode( "euc-jp", $xp->findvalue("//Binding") );
        $rdat{catalog} = $rdat{asin};
        $rdat{getdate} = localtime();
        $ua            = new LWP::UserAgent;
        $ua->timeout(60);
        $response = LWP::Simple::get( $rdat{medium_img} );
        open( IMG, "> $CACHE_DIR/image/$rdat{asin}.jpg" );
        print IMG $response;
        close(IMG);
        untie %rdat;
    }

    tie %rdat, "DB_File", "$CACHE_DIR/$itemid", O_RDONLY, 0644, $DB_HASH;
    open( LOG, ">> $CACHE_DIR/log" );
    print LOG $rdat{getdate}, " Success ", $xp, "\n", %rdat, "\n\n";
    close(LOG);
    return $xp;
}
1;
__END__

