-- 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://api-ssl.bitly.com/v3/shorten'
local access_token = cred_data.bitly_access_token

function create_bitlink (long_url, domain)
  local url = BASE_URL..'?access_token='..access_token..'&domain='..domain..'&longUrl='..long_url..'&format=txt'
  local text,code  = https.request(url)
  if code ~= 200 then return 'FEHLER: '..text end
  return text
end

function run(msg, matches)
  if matches[2] == nil then
    long_url = url_encode(matches[1])
	domain = 'bit.ly'
  else
    long_url = url_encode(matches[2])
	domain = matches[1]
  end
  return create_bitlink(long_url, domain)
end

return {
  description = "Kürzt einen Link", 
  usage = {
    "/short [Link]: Kürzt einen Link mit Bitly",
	"/short [j.mp|bit.ly|bitly.com|andib.tk] [Link]: Kürzt einen Link mit der ausgewählten Kurz-URL"
  },
  patterns = {
  	"^/short (j.mp) (https?://[%w-_%.%?%.:/%+=&]+)$",
	"^/short (bit.ly) (https?://[%w-_%.%?%.:/%+=&]+)$",
	"^/short (bitly.com) (https?://[%w-_%.%?%.:/%+=&]+)$",
	"^/short (andib.tk) (https?://[%w-_%.%?%.:/%+=&]+)$",
	"^/short (https?://[%w-_%.%?%.:/%+=&]+)$"
  },
  run = run 
}

end