local openingsmoe = {}

openingsmoe.triggers = {
  "openings.moe/%?video=(.*).webm"
}

function openingsmoe:get_opening(opening)
  local url = 'http://openings.moe/api/details.php?file='..opening..'.webm'
  local res,code  = http.request(url)
  local data = json.decode(res)
  if code ~= 200 then return nil end
  if not data.success then return nil end
 
  local number = data.title
  local title = data.source
  local song_title = data.song.title
  local song_artist = data.song.artist
  local url = 'http://openings.moe/video/'..data.filename

  local text = '<b>'..number..'</b> aus <b>'..title..'</b>\n<b>Song:</b> '..song_title..' von '..song_artist..'\n<a href="'..url..'">Direktlink</a>'

    return text
end

function openingsmoe:action(msg, config, matches)
  local opening = matches[1]
  local text = openingsmoe:get_opening(opening)
  if not text then
    utilities.send_reply(msg, config.errors.connection)
	return
  end
  utilities.send_reply(msg, text, 'HTML')
end

return openingsmoe