-- 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://api.soundcloud.com/resolve.json'

function get_soundcloud_data (sc_url)
  local client_id = cred_data.soundcloud_client_id
  local url = BASE_URL..'?url=http://soundcloud.com/'..sc_url..'&client_id='..client_id
  local res,code  = http.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data
end

function send_soundcloud_data(data, receiver)
	local title = data.title
    local description = data.description
    local user = data.user.username
	local user = 'Unbekannt'
	local genre = data.genre
	local playback_count = data.playback_count
	milliseconds = data.duration
	
	-- convert ms to mm:ss
	totalseconds = math.floor(milliseconds / 1000)
    milliseconds = milliseconds % 1000
    seconds = totalseconds % 60
    minutes = math.floor(totalseconds / 60)
    hours = math.floor(minutes / 60)
    minutes = minutes % 60
	local duration = string.format("%02d:%02d",  minutes, seconds)
	
    local text = '"'..title..'" von "'..user..'"\n(Tag: '..genre..', '..duration..' Minuten; '..playback_count..' mal angehört)\n'..description
	send_msg(receiver, text, ok_cb, false)
end

function run(msg, matches)
  local sc_url = matches[1]
  local data = get_soundcloud_data(sc_url)
  local receiver = get_receiver(msg)
  send_soundcloud_data(data, receiver)
end

return {
  description = "Sendet Soundcloud-Info.", 
  usage = "Link zu SoundCloud-Track",
  patterns = {"soundcloud.com/([A-Za-z0-9-/-_-.]+)"},
  run = run 
}

end