-- This is a proprietary plugin, property of Andreas Bielawski, (c) 2015 <andi (dot) b (at) outlook (dot) de>
-- DO NOT USE WITHOUT PERMISSION

do

local BASE_URL = 'https://www.googleapis.com/books/v1'


local function get_books_data (term)
  local url = BASE_URL..'/volumes?q='..term..'&maxResults=3&fields=totalItems,items%28volumeInfo%28title,authors,publisher,publishedDate,pageCount,canonicalVolumeLink%29,saleInfo%28country,listPrice%29%29'
  local res,code  = https.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data
end

local function send_books_data(data, receiver)
  local text = ""
  for book in pairs(data.items) do
    text = text..'"'..data.items[book].volumeInfo.title..'"'
	  
	if data.items[book].volumeInfo.publisher == nil and data.items[book].volumeInfo.pageCount ~= nil then
	  text = text..'\n'..data.items[book].volumeInfo.authors[1]..', '
	else
	  text = text..'\n'..data.items[book].volumeInfo.authors[1]..''
	end

	if data.items[book].volumeInfo.authors[1] == data.items[book].volumeInfo.publisher then data.items[book].volumeInfo.publisher = nil end
	  
	if data.items[book].volumeInfo.publisher then
	  if data.items[book].volumeInfo.pageCount then
		text = text..', '..data.items[book].volumeInfo.publisher..', '
      else
	    text = text..', '..data.items[book].volumeInfo.publisher
      end
	end
	  
	if data.items[book].volumeInfo.pageCount then
	  text = text..data.items[book].volumeInfo.pageCount..' Seiten'
	end
	  
	if data.items[book].volumeInfo.publishedDate then
	  text = text..', erschienen '..data.items[book].volumeInfo.publishedDate
	end
	  
	if data.items[book].saleInfo.listPrice then
	  text = text..'\nPreis: '..data.items[book].saleInfo.listPrice.amount..' '..data.items[book].saleInfo.listPrice.currencyCode
	end
	  
	text = text..'\n'..data.items[book].volumeInfo.canonicalVolumeLink
    text = text..'\n\n'
  end
  send_large_msg(receiver, text, ok_cb, false)
end

local function run(msg, matches)
  local term = URL.escape(matches[1])
  local data = get_books_data(term)
  local receiver = get_receiver(msg)
  send_books_data(data, receiver)
end

return {
  description = "Sucht nach Büchern in Google Books.", 
  usage = "/books [Suchbegriff]: Sucht nach Büchern in Google Books",
  patterns = {"^/books (.*)$"},
  run = run 
}

end