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

require "amarok"

# initilization on load
sectionName="lastfm_artist_info"
AMAROK.addCustomSection(sectionName)

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

def fetchArtistInfo()
	
	sectionName="lastfm_artist_info"
	
	# provide feedback to the user while we do out work
	AMAROK.setCustomSection(sectionName,"Loading...")

	# fetch current data for the song
	artist = AMAROK.getArtist().strip()
	title = AMAROK.getTitle().strip()
	
	# set the section title to something more meaningful
	AMAROK.setCustomSectionTitle(sectionName,"Last.fm - About #{artist}")
	
	# check the cache
	key="lastfm-artistinfo-#{artist}"
	res = AMAROK.getCache(key).strip()
	if res.to_s() != ""
		AMAROK.setCustomSection(sectionName,res)
		return
	end
	
	# remove spaces, url's don't like them
	artist.gsub!(" ","+")
	title.gsub!(" ","+")
	artist.gsub!("&","%2526")
	title.gsub!("&","%2526")
	
	# query the page
	body = curl("http://www.last.fm/music/#{artist}/+wiki")
	if body == nil or body == ""
		AMAROK.clearCustomSection(sectionName)
		return
	end
	
	#puts body
	
	# pull the names out of the body of the text
	body.gsub!("\n","")
	res = /<a href="\/wiki\/">View wiki recent changes page<\/a>[\t ]*<\/p>[\t ]*<\/div>(.*?)<div *style="margin-top:20px; border-top:1px solid #CCC; padding-top:10px;">/.match( body )
	#res = /<\/div>(.*?)<div style="margin-top:20px; border-top:1px solid #CCC; padding-top:10px;">/.match( body )
	
	#puts res
	
	#body.scan( /<a title="(.*?)"/ )
	
	if res != nil
		
		# possible add links here
		
		# join all the names together
		#artists = []
		#names.each do |name|
		#	artists.push(name)
		#end
		#html = artists.join(", ")
		
		# hand off to amarok
		AMAROK.setCustomSection(sectionName,res[1])
		#AMAROK.setCache(key,res)
		return
	end
	
	# failed to work
	AMAROK.clearCustomSection(sectionName)
end

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

    case command
    	when "trackChange"
    		fetchArtistInfo()
    end
end