# Bryan Schumaker (10/24/2010)

import libsaria
from libsaria import sources
from libsaria import web
from libsaria import xm
from libsaria import callbacks
from libsaria import storage
from libsaria.storage import cache
import threading

file_id   = libsaria.path.file_id
pref_attr = xm.find_preferred_attribute

pref_sizes = ["extralarge", "large", "medium", "small"]

APIROOT = "http://ws.audioscrobbler.com/2.0/"
APIKEY = "2c76f85a6704efd74b5a358821284ef9"
SECRET = "3a6012bfb627b60a884cf33fc044885c"


class LastFmRequest(dict):
	def __init__(self, method):
		self.method = method

	def print_file(self, file):
		for line in file:
			print line.strip()
		file.seek(0)

	def place(self, printfile=False):
		url = web.Url(APIROOT + "?method=" + self.method)
		url["api_key"] = APIKEY
		for param in self:
			url[param] = self[param]
		try:
			file = url.open()
		except:
			return None
		if file == None:
			return None
		if printfile==True:
			self.print_file(file)
		doc = xm.parse( file )
		lfm = xm.child(doc)
		if xm.attributes(lfm)["status"] == "ok":
			return xm.child(lfm)
		else:
			return None

def lfm_cache_album(artist, album, title):
	req = LastFmRequest("album.getInfo")
	req["album"]  = album
	req["artist"] = artist
	doc = req.place()
	if doc == None:
		return False
	node = pref_attr(doc, "image", "size", pref_sizes)
	node = xm.child(node)
	if node == None:
		return
	try:
		url = web.Url(node.data)
		text = url.open().read()
		return text
	except:
		pass
	return None

def get_album_art(attrs):
	file = cache.get_item(attrs["artist"], attrs["album"], attrs["title"], "Folder.jpg", lfm_cache_album, "images/ocarina.png")
	if file != None:
		callbacks.get_art(file, attrs["id"])

def get_artwork(attrs):
	threading.Thread(target=get_album_art, args=(attrs,)).start()

def test_artwork(attrs):
	path = cache.test_item(attrs["artist"], attrs["album"], "Folder.jpg", "images/ocarina.png")
	if path == "images/ocarina.png":
		get_artwork(attrs)
	return path

def set_artwork(artist, album, img_path):
	cache.copy_in_file(artist, album, "Folder.jpg", img_path)
