#!/usr/bin/python2.4
#
import os
import sys
import string
import httplib
import xml.dom.minidom

def main(args):
  # process command line args
  if len(args) > 1:
    asin = args[1]
    if asin == "help" or asin == "--help":
      help(args[0])
      sys.exit(0)
  else:
    asin = "0321200683"
  if len(args) > 2:
    tld = args[2]
  else:
    tld = "com"

  print("Reviews for ISBN %s" % asin)
  try:
    dom = GetAmazonData("<<your amazon token>>", asin, tld)
  except Exception:
    print("Unable to connect to Amazon")
    sys.exit(0)
  print(getTitle(dom))
  num = GetNumReviews(dom)
  oldnum = ReadNumReviews(asin)
  if (num != oldnum):
    PrintReviews(dom)
    WriteNumReviews(asin, num)
    sys.exit(1)
  else:
    print("no new reviews")
    sys.exit(0)

### Usage

def help(name):
  print "Checks Amazon for reviews and if there are new ones, prints them to stdout"
  print "Returns 1 if new reviews were found, 0 otherwise."
  print ""
  print "Usage:"
  print "%s asin         - asin is the Amazon identifier, e.g. an ISBN" % os.path.basename(name)
  print "%s asin country - country is a local property, such as 'de'" % os.path.basename(name)
  print "%s help         - this info" % os.path.basename(name)
  
### File Operations  

def WriteNumReviews(asin, num):
  file=open(FileName(asin), 'w')
  file.write("%s,%s" % (asin, num))
  file.flush

def ReadNumReviews(asin):
  if os.path.isfile(FileName(asin)):
    file=open(FileName(asin), 'r')
    s = file.readline()  
    tokens = string.split(s, ",")
    return tokens[1]
  else:
    return -1
  
def FileName(asin):
  return '/tmp/amazonstats-%s.txt' % asin

### DOM Operations

def GetAmazonData(key, isbn, tld):
  c = httplib.HTTPConnection("ecs.amazonaws.%s" % tld)
  c.request('GET', '/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Reviews,ItemAttributes&AWSAccessKeyId=%s&ItemId=%s' % (key, isbn))
  r = c.getresponse()
  r.status
  b = r.read()
  dom = xml.dom.minidom.parseString(b)
  return dom

# returns UTF-8 encoded string
def getText(node):
    rc = ""
    for node in node.childNodes:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

def GetNumReviews(dom):
    review = dom.getElementsByTagName("TotalReviews")
    if len(review) > 0:
      return getText(review[0])
    else:
      return 0

def getTitle(dom):
  if len(dom.getElementsByTagName("ItemAttributes")) > 0:
    return getText(dom.getElementsByTagName("ItemAttributes")[0].getElementsByTagName("Title")[0])
  else:
    print("Item not found")
    sys.exit(0)

### Printing / Formatting

def PrintReviews(dom):
  print("")
  for review in dom.getElementsByTagName("Review"):
    print getText(review.getElementsByTagName("Date")[0]) + ": " + getText(review.getElementsByTagName("Rating")[0]) + " Stars"
    print getText(review.getElementsByTagName("Summary")[0]).encode('latin-1')
    print getText(review.getElementsByTagName("Content")[0]).encode('latin-1')
    print('----')

if __name__ == '__main__':
  main(sys.argv)
