# Bryan Schumaker (12/12/2010)

import libsaria

library = None
source  = None

queue    = []
song_set = set()

filtered = False
visible  = None

def add_id(id):
	if id not in song_set:
		queue.append(id)
		song_set.add(id)

def add_ids(ids):
	for id in ids:
		add_id(id)

def rm_id(id):
	if id in queue:
		queue.remove(id)
		song_set.remove(id)

def rm_ids(ids):
	for id in ids:
		rm_id(id)

def reset():
	global queue
	global song_set
	queue    = []
	song_set = set()

def init():
	global library
	global source

	import library
	source = libsaria.sources.Source()
	source.get_attrs  = library.get_attrs
	source.set_attr   = library.set_attr
	source.get_cur_id = get_cur_id
	source.save       = save

def save():
	pass

def init_bg():
	init()

def walk():
	for id in queue:
		yield id

def walk_queue(*attrs):
	res = []
	for id in walk():
		res.append(library.get_attrs(id, *attrs))
	return res

def filter(text):
	global visible, filtered
	if len(text) > 0:
		visible  = song_set.intersection(library.test_filter(text))
		filtered = True
	else:
		visible  = song_set
		filtered = False

def get_cur_id():
	return cur_id

def is_visible(id):
	if filtered == True:
		return id in visible
	return True

def num_visible():
	if filtered == True:
		return len(visible)
	return len(queue)

def load_id(id):
	global cur_id
	cur_id = id
	path = library.get_attrs(id, "filepath")
	rm_id(id)
	return source.load_file(path)

def play_id(id):
	if load_id(id) == True:
		libsaria.controls.play()
		return True
	return False

def next():
	global cur_id
	if len(queue) == 0:
		return None
	cur_id = queue.pop(0)
	song_set.remove(cur_id)
	source.set_current()
	return library.get_attrs(cur_id, "filepath")

