#!/usr/iekei/ruby/bin/ruby
=begin
 [asin:11111111]
 Ȥѥ󤬤AmazonܤβԤȥȥִ롣
 Ѿ
  ¸ѥå
   uconv
   soap4r
  Amazon Web ServiceȤˤϡDevelopper ID(Developper Talken)
  ɬפǤ(Asociete ID⤢äۤɤ褦Ǥ)
 ()
 <Ѵ>

 [asin:4906391702]

 <Ѵ>

  <div class="amazon">
    <a href="http://www.amazon.co.jp/exec/obidos/ASIN/4906391702/ref=nosim/XXXXXXXXXX-XX/">
      <img src="http://images-jp.amazon.com/images/P/4906391702.09.MZZZZZZZ.jpg" alt="䤵EmacsLispֺ" title="䤵EmacsLispֺ">
    </a><br>
     ͺ / <a href="http://www.amazon.co.jp/exec/obidos/ASIN/4906391702/ref=nosim/XXXXXXXXXX-XX">䤵EmacsLispֺ</a>
  </div>

=end

require 'uconv'
require 'kconv'
require 'soap/wsdlDriver'
require 'AmazonSearch.rb'

$tag = ''    # Amazon Asociete ID 
$devtag = '' # Amazon WebService Developper ID(Talken)

# AmazonWebӥѥ饹(amazon.com)
class AmazonWebService

  def initialize(tag , devtag)
    @devtag = devtag
    @tag = tag
    @amazon = SOAP::WSDLDriverFactory.new(wsdl).createDriver
    @amazon.generate_explicit_type = true
  end
  attr_reader :amazon

  def locale
    nil
  end

  def wsdl
    'http://soap.amazon.com/schemas3/AmazonWebServices.wsdl'
  end

  def keyword_search(text)
    req = KeywordRequest.new(text, '1', 'book', @tag, "lite", @devtag)
    req.locale = locale if locale
    @amazon.KeywordSearchRequest(req).Details
  end

  def asin_search(text)
    req = AsinRequest.new(text, @tag, "lite", @devtag)
    req.locale = locale if locale
    @amazon.AsinSearchRequest(req).Details
  end

end

# amazon.co.jp 饹
class AmazonJP < AmazonWebService
  def locale
    'jp'
  end

  def wsdl
    'http://soap.amazon.co.jp/schemas3/AmazonWebServices.wsdl'
  end
end

# -e ץĤΤȤ EUC-JPΤޤ޽

$euc = false
while /^-\w/ =~ ARGV[0]
  case ARGV[0]
    when /^-e$/
    $euc=true;
  end
  ARGV.shift
end
$euc = true if /euc|-e$/ =~ $0

$amazon = AmazonJP.new($tag,$devtag)

filename = ARGV[0]
file = open(filename)

while line=file.gets do
  # ºݤνEUC-JPˤƹԤ
  line = Kconv::toeuc(line)
  str = nil
  if /\[asin:([0-9]+)\]/ =~ line
    # SORPϢUTF-9ǽԤǸEUC-JPѴ
    item=$amazon.asin_search($1)[0]
    str = "\n<div class=\"amazon\">\n"
    str += "  <a href=\"http://www.amazon.co.jp/exec/obidos/ASIN/#{item.Asin}/ref=nosim/#{$tag}/\">\n"
    str += "    <img src=\"#{item.ImageUrlMedium}\" alt=\"#{item.ProductName}\" title=\"#{item.ProductName}\">\n"
    str += "  </a><br>\n"
    str += "  #{item.Authors.join(", ")} / " if item.Authors != nil  
    str += "<a href=\"http://www.amazon.co.jp/exec/obidos/ASIN/#{item.Asin}/ref=nosim/#{$tag}/\">#{item.ProductName}</a>\n"
    str += "</div>\n"
    str = Uconv.u8toeuc(str)
  end
  line.sub!(/\[asin:([0-9]+)\]/,str) if str != nil

  print (if $euc then line else Kconv::tojis(line) end)

end
