# Bryan Schumaker (8/8/2010)

import libsaria
from libsaria import callbacks
exists  = libsaria.path.exists
expand  = libsaria.path.expand

import library
import playlist
import queue
import attrs

attrs.load_dattrs()
cur_id = None

def get_cur_id():
	return cur_id

def inc_count():
	attrs.inc_count(get_cur_id())

def find_attrs(file, *attr_list):
	if file == None:
		return
	track = library.track.Track(file)
	if track == None:
		return
	id    = library.update.song_id(file)
	get   = track.__dict__.get
	res   = []
	for attr in attr_list:
		if attr == "id":
			res.append(id)
		elif attr == "like":
			res.append(attrs.get_dattr(id, "like"))
		elif attr == "count":
			res.append(attrs.get_count(id))
		else:
			res.append(get(attr))
	return res

def find_all_attrs(file, attrs):
	if file == None:
		return False
	track = library.track.Track(file)
	if track == None:
		return False
	id = library.update.song_id(file)
	attrs.update(track.__dict__)
	attrs["id"] = id

# Function pointer to avoid unnecessary lookups for a common function
get_attrs_id = library.get_attrs

def get_attrs(*attrs):
	# I should probably get a lock here...
	global cur_id
	res = None
	if cur_id:
		res = get_attrs_id(cur_id, *attrs)
	if res == None:
		cur_id = None
		file = libsaria.audio.get_cur_file()
		res = find_attrs(file, *attrs)
	if res == None:
		res = [None] * len(attrs)
	return res

def all_attrs():
	global cur_id
	res   = {}
	found = False
	if cur_id:
		found = library.all_attrs(cur_id, res)
	if found == False:
		cur_id = None
		file   = libsaria.audio.get_cur_file()
		found  = find_all_attrs(file, res)
	if found != False:
		res["like"]  = attrs.get_like(res["id"])
		res["count"] = attrs.get_count(res["id"])
		res["art"]   = libsaria.path.lastfm.test_artwork(res)
	return res

def filter(text):
	visible = library.filter(text)
	playlist.set_visible(visible)
	queue.set_visible(visible)
	callbacks.refilter()

def is_visible(id):
	return library.is_visible(id)

def set_attr(attr, value):
	id = get_cur_id()
	if id:
		attrs.set_dattr(id, attr, value)

def make_library(path):
	path = expand(path)
	if not exists(path):
		return
	library.add_path(path)
	library.update_lib()

def play_id(id):
	global cur_id
	cur_id = id
	file   = all_attrs()["filepath"]
	queue.rm_ids([id])
	libsaria.controls.load(file)
	libsaria.controls.play()

def next():
	global cur_id
	id = queue.next()
	if id == None:
		id = playlist.get_next(cur_id)
	if id != None:
		cur_id = id
		return all_attrs()["filepath"]

def list_source(list_func, *attrs):
	ret = []
	append    = ret.append
	for id in list_func():
		append(get_attrs_id(id, *attrs))
	return ret

def list_library(*attrs):
	return list_source(library.list_ids, *attrs)

def list_playlist(*attrs):
	return list_source(playlist.list_ids, *attrs)

def list_queue(*attrs):
	return list_source(queue.list_ids, *attrs)
