-- 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 = 'https://www.googleapis.com/urlshortener/v1'

local function get_shortlink_data (shorturl)
  local apikey = cred_data.google_apikey
  local url = BASE_URL..'/url?key='..apikey..'&shortUrl=http://goo.gl/'..shorturl..'&projection=FULL'
  local res,code  = https.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data
end

local function send_shortlink_data(data, receiver)
  local longUrl = data.longUrl
  local shortUrlClicks = data.analytics.allTime.shortUrlClicks
  local text = longUrl..'\n'..shortUrlClicks..' mal geklickt'
  send_msg(receiver, text, ok_cb, false)
end

local function run(msg, matches)
  local shorturl = matches[1]
  local data = get_shortlink_data(shorturl)
  local receiver = get_receiver(msg)
  send_shortlink_data(data, receiver)
end

return {
  description = "Sendet Goo.gl-Info.", 
  usage = {"goo.gl URL"},
  patterns = {"goo.gl/([A-Za-z0-9-_-]+)"},
  run = run 
}

end
