# Bryan Schumaker (8/8/2010)

import libsaria
exists  = libsaria.path.exists
expand  = libsaria.path.expand

import library
import playlist
import queue

controls = libsaria.controls

cur_source = None
cur_id = None

LIBRARY, PLAYLIST, QUEUE = range(3)

class Source:
	def __init__(self):
		self.get_attrs  = None
		self.set_attr   = None
		self.get_cur_id = None
		self.save       = None

	def set_current(self):
		global cur_source
		cur_source = self

	def load_file(self, path):
		global cur_source
		# I should probably get a lock here...
		try:
			self.set_current()
			controls.load(path)
			return True
		except:
			return  False

def get_attrs(*attrs):
	# I should probably get a lock here...
	if cur_id:
		return cur_source.get_attrs(cur_id, *attrs)
	return -1

def set_attr(attr, value):
	if cur_source:
		cur_source.set_attr(cur_id, attr, value)
		cur_source.save()

def new_source(path, bg=True):
	global library
	path = expand(path)
	if not exists(path):
		return 0
	library.scan(path)
	libsaria.callbacks.new_source()

def play_id(id):
	global cur_id
	cur_id = id
	library.play_id(id)
	queue.rm_ids([id])

def next():
	global cur_id
	cur_id = queue.next()
	if cur_id == None:
		cur_id = playlist.next()
	return library.get_attrs(cur_id, "filepath")

def list_source(source, *attrs):
	ret = []
	list_func = None
	get_attrs = library.get_attrs
	append    = ret.append
	if source == QUEUE:
		list_func = queue.list
	if list_func != None:
		for id in list_func():
			append(get_attrs(id, *attrs))
	return ret

def list_queue(*attrs):
	return list_source(QUEUE, *attrs)
