-- 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_db(tag)
  local BASE_URL = 'http://danbooru.donmai.us'
  local url = BASE_URL..'/posts.json?tags='..tag
  local b,c = http.request(url)
  if c ~= 200 then return nil end
  local db = json:decode(b)
  -- truly randomize
  math.randomseed(os.time())
  -- random max json table size
  local i = math.random(#db)
  local link_image = BASE_URL..db[i].file_url
  return link_image
end

local function run(msg, matches)
  local tag = matches[1]
  local tag = string.gsub(tag, " ", '_' )
  local tag = string.gsub(tag, ":", '%%3A' )
  local receiver = get_receiver(msg)
  local url = get_db(tag)
  if string.ends(url, ".gif") or string.ends(url, ".zip") or string.ends(url, ".webm") then
    send_document_from_url(receiver, url)
  else
	send_photo_from_url(receiver, url, send_title, {receiver, title})
  end
    return "Source: "..url
end

return {
  description = "Sendet ein zufälliges Bild von Danbooru.", 
  usage = {"/danbooru [Tags]","/db [Tags]"},
  patterns = {"^/danbooru (.*)$","^/db (.*)$"},
  run = run 
}

end