# Bryan Schumaker (11/23/2010)

libsaria = None
sources  = None
library  = None
playlist = None
queue    = None

audio  = None
call   = None
invite = None
prefs  = None
expand = None
exists = None

pause_after = False

def init():
	global libsaria
	global prefs

	import libsaria
	prefs = libsaria.prefs
	libsaria.init_pref("libsaria.random", False)

def init2():
	global call
	global audio
	global invite
	global sources
	global library
	global playlist
	global expand
	global exists
	global queue

	call     = libsaria.event.call
	invite   = libsaria.event.invite
	expand   = libsaria.path.expand
	exists   = libsaria.path.exists
	sources  = libsaria.sources
	library  = sources.library
	playlist = sources.playlist
	queue    = sources.queue

	from libsaria.audio import audio
	invite("PREEOS", pause)
	invite("POSTEOS", catch_eos)

def pick_next():
	global pause_after
	file = queue.next()
	if file == None:
		file = playlist.next()
	load(file)
	if pause_after == True:
		pause()
	else:
		play()
	pause_after = False

def catch_eos(*args):
	library.inc_count()
	return call("NEXT", pick_next)

def next():
	return call("NEXT", pick_next)

def play():
	return call("PLAY", audio.play)

def pause():
	return call("PAUSE", audio.pause)

def playing():
	return audio.get_state() == audio.gst.STATE_PLAYING

def do_pause_after(*args):
	global pause_after
	pause_after = True

def toggle_play():
	if audio.get_state() == audio.gst.STATE_PAUSED:
		play()
	else:
		pause()

def stop():
	return call("STOP", audio.stop)

def seek_forward():
	libsaria.audio.seek_sec(5)

def seek_backward():
	libsaria.audio.seek_sec(-5)

def set_volume(prcnt):
	return call("SETVOLUME", audio.set_volume, prcnt)

def set_rand(rand):
	prefs.set_pref("libsaria.random", rand)

def set_like(like=None):
	return call("SETLIKE", sources.set_attr, "like", like)

def get_like():
	return sources.get_attrs("like")

def load(file):
	file = expand(file)
	if not exists(file):
		return False
	return call("LOAD", audio.load, file)
