import sys
from decorator import decorator
from monkeypatch import monkeypatch
from pyaws import ecs

# ins and outs
# these can be modified fairly extensively,
# to control exactly what the Amazon API pukes out
rs_fetch = """Request,ItemIds,Images,Tracks,Accessories,Small,Medium,Large,Variations,VariationImages,VariationMinimum,VariationSummary,TagsSummary,Tags,VariationMatrix,VariationOffers,ItemAttributes,SalesRank,Subjects,Reviews,EditorialReview,Collections,ShippingCharges,BrowseNodes"""  ## holy shit
rs_search = """Request, ItemIds, Small, Medium, Large, ItemAttributes, Tracks, EditorialReview, SalesRank, Images"""

class Amazon:
	
	auth_init = False
	
	def __init__(self, ecsref=None):
		self.ecs = ecsref
	
	@decorator
	def ecsauth(f, *args, **kwargs):
		self = args[0]
		if not self.auth_init:
			self.ecs.setLicenseKey("YOUR_AWS_KEY")
			self.ecs.setSecretAccessKey("YOUR_SUPER_SECRET_AWS_PRIVATE_KEY")
			self.auth_init = True
		return f(self, *args, **kwargs)
	
	@ecsauth
	def search(*args, **kwargs):
		self = args[0] # ugh
		search = kwargs.get('q', None)
		searchidx = kwargs.get('idx', 'Books')
		rsgroup = kwargs.get('rs', rs_search)
		aq = self.ecs.ItemSearch(search, SearchIndex=searchidx, ResponseGroup=rsgroup)
		aqout = []
		i = e = 0
		while i < 25:
			try:
				a = aq.next()
				i += 1
			except IndexError:
				e += 1
			except StopIteration:
				break
			else:
				aqout += [a]
		return aqout

	@ecsauth
	def fetch(self, *args, **kwargs):
		qid = '%s' % kwargs.get('qid', "-1")
		idtype = kwargs.get('idtype', 'ASIN')
		rsgroup = kwargs.get('rg', rs_fetch)
		idx = kwargs.get('idx', 'Books')
		aqout = []

		if idtype == "ASIN":
			idx = None
		qid = qid.replace('-', '')

		aq = self.ecs.ItemLookup("%s" % qid, IdType=idtype, SearchIndex=idx, ResponseGroup=rsgroup)

		i = e = 0
		while True:
			try:
				a = aq.next()
				i += 1
			except IndexError:
				e += 1
			except StopIteration:
				break
			else:
				aqout += [a]
		return aqout

aws = Amazon(ecs)