-- 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 function get_r34_info(tag)
  local limit = 100 -- number of posts to return (higher = more choices for random, but longer load times, hard limit of 100 posts)
  local BASE_URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D%27http%3A%2F%2Frule34.xxx%2Findex.php%3Fpage%3Ddapi%26s%3Dpost%26q%3Dindex%26limit%3D'..limit..'%26tags%3D'
  local END_URL = '%27&format=json'
  local url = BASE_URL..tag..END_URL
  local res,code  = https.request(url)
  local r34 = json:decode(res).query.results.posts.post
  if code ~= 200 then return "HTTP-Fehler" end
  
    -- truly randomize
  math.randomseed(os.time())
  -- random max json table size
  local i = math.random(#r34)
  local url = r34[i].file_url
  local source_url = 'Source: http://rule34.xxx/index.php?page=post&s=view&id='..r34[i].id
  return url, source_url
end

local function run(msg, matches)
  local tag = matches[1]
  local tag = string.gsub(tag, " ", '_')
  local tag = string.gsub(tag, ":", '%%3A')
  local tag = string.gsub(tag, "+", '%%2B')
  local receiver = get_receiver(msg)
  local url, id = get_r34_info(tag)
  local cb_extra = {
    receiver=receiver,
    url=url
  }
  if string.ends(url, ".gif") then
    send_msg(receiver, id, send_document_from_url_callback, cb_extra)
  else
	send_msg(receiver, id, send_photo_from_url_callback, cb_extra)
  end
end

return {
  description = "Sendet zufälliges Bild von rule34.xxx", 
  usage = "#r34 [Tag]: Sendet zufälliges Bild von rule34.xxx",
  patterns = {"^#r34 (.*)"},
  run = run 
}

end