#!/usr/bin/ruby -I/home/teknomunk/.kde/share/apps/amarok/

require "amarok"

sectionName="lastfm_tag_cloud"
sectionTitle="Last.fm - Tag Cloud"
AMAROK.addCustomSection(sectionName)
AMAROK.setCustomSectionTitle(sectionName,sectionTitle)

def curl( url )
	return `curl "#{url}" 2>/dev/null`
end

def fetchTags()
	sectionName="lastfm_tag_cloud"
	
	AMAROK.setCustomSection(sectionName,"Loading...")
		
	# fetch current data for the song
	artist = AMAROK.getArtist().strip()
	title = AMAROK.getTitle().strip()
	artist.gsub!(" ","+")
	title.gsub!(" ","+")
	artist.gsub!("&","%2526")
	title.gsub!("&","%2526")
	
	# check the cache for valid data
	key="lastfm-cloudtag-#{artist}#{title}"
	res = AMAROK.getCache(key).strip()
	if res.to_s() != ""
		AMAROK.setCustomSection(sectionName,res)
		return
	end
	
	# get the page from last.fm
	body = curl( "http://www.last.fm/music/#{artist}/_/#{title}" )
	if body == nil
		AMAROK.setCache(key,"")
		AMAROK.clearCustomSection(sectionName)
		return
	end
	
	# search for the tags
	body.gsub!("\n","")
	tags = /User Tags<\/h3>.*?<div.*?>(.*?)<\/div>/.match( body.to_s() )
	
	if tags == nil
		# try the artist's page
		body = curl( "http://www.last.fm/music/#{artist}/" )
		
		# search for the tags again
		body.gsub!("\n","")
		tags = /User Tags<\/h3>.*?<div.*?>(.*?)<\/div>/.match( body.to_s() )
	end
	
	if tags != nil
		# get the results
		res = tags[1]
		
		# cleanup the html a bit
		res.gsub!(/[\t\n]*/,"")
		res.gsub!("&nbsp;","")
		res.gsub!("</a>","</a>&nbsp;&nbsp;&nbsp;");
		res.gsub!(/  +/,"")
		
		# This fixes amarok's html text size problem
		res.gsub!(
			/<span style="font-size: ([0-9]*)px;"><a style="/,
			'<a style="font-size: \1px; '
			)
		
		AMAROK.setCustomSection(sectionName,res)
		AMAROK.setCache(key,res)
		return
	end
	
	AMAROK.clearCustomSection(sectionName)
end

loop do
    message = gets().chomp()
    command = /[A-Za-z]*/.match( message ).to_s()

    case command
    	when "trackChange"
    		fetchTags()
    end
end