-- 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 = 'http://ponyfac.es/api.json'

local function get_ponyface(tag)
  local url = BASE_URL..'/tag:'..tag
  local b,c = http.request(url)
  if c ~= 200 then return nil end 
  local pf = json:decode(b).faces
  -- truly randomize
  math.randomseed(os.time())
  -- random max json table size
  local i = math.random(#pf)
  local link_image = pf[i].image
  return link_image
end

local function get_ponyface_by_id(id)
  local url = BASE_URL..'/id:'..id
  local res,code  = http.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data.faces[1].image
end

local function run(msg, matches)
  if tonumber(matches[1]) ~= nil then
    local id = matches[1]
	url = get_ponyface_by_id(id)
  else
    local tag = matches[1]
    url = get_ponyface(tag)
  end
  local receiver = get_receiver(msg)
  if url == "HTTP-FEHLER" then
    return "Kein Ponyface gefunden :("
  else
    send_photo_from_url(receiver, url)
  end
end

return {
  description = "Sendet zufälliges Ponyface", 
  usage = "/ponyface [Tags]","/pf [Tags]",
  patterns = {"^/ponyface (.*)$","^/pf (.*)$","ponyfac.es/(%d+[%d%.]*)"},
  run = run 
}

end