-- 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_dp(tag)
  local BASE_URL = 'https://derpiboo.ru/'
  local apikey = ""
  
  -- Ohne API-Key: Safe for work - mit API-Key: Not safe for work
  if apikey == nil then
    url = BASE_URL..'/search.json?q='..tag
  else
    url = BASE_URL..'/search.json?key='..apikey..'&q='..tag
  end
  
  local b,c = https.request(url)
  if c ~= 200 then return nil end
  local dp = json:decode(b).search
  -- truly randomize
  math.randomseed(os.time())
  -- random max json table size
  local i = math.random(#dp)
  local link_image = 'https:'..dp[i].image
  source = 'https://derpiboo.ru/'..dp[i].id_number
  return link_image
end

local function run(msg, matches)
  local tag = matches[1]
  local tag = string.gsub(tag, " ", '+' )
  local receiver = get_receiver(msg)
  local url = get_dp(tag)
  send_photo_from_url(receiver, url, send_title, {receiver, title})
  return "Source: "..source
end

return {
  description = "Sendet zufälliges Bild von Derpibooru.", 
  usage = {"/derpibooru [Tags]","/dp [Tags]"},
  patterns = {"^/derpibooru (.*)$","^/dp (.*)$"},
  run = run 
}

end