# Bryan Schumake (8/7/2010)

__all__ = ['audio']

import libsaria
call = libsaria.event.call
expand = libsaria.path.expand
exists = libsaria.path.exists
audio  = None
tdelta = None

def ls_init():
	libsaria.init_pref("libsaria.audio.volume", 1.0)
libsaria.event.invite("POSTINIT", ls_init)

def init():
	global tdelta
	global audio

	from datetime import timedelta as tdelta
	import audio
	audio.init()


def end_of_song():
	global audio
	return call("EOS", audio.reset)


def seek(prcnt):
	global audio
	return call("SEEK", audio.seek, prcnt)


def seek_sec(sec):
	global audio
	dur = audio.duration()
	if dur > 0:
		prcnt = get_progress() + (1 * sec * 1000000000) / audio.duration()
		if prcnt > 1:
			prcnt = 1
		if prcnt < 0:
			prcnt = 0
		seek(prcnt)


def get_progress():
	global audio
	dur = audio.duration()
	if dur > 0:
		return audio.position() / dur
	return 0


def get_time():
	global audio
	global tdelta
	pos = audio.position()
	if pos == 0:
		return ""
	pos /= 1000
	time = str(tdelta(microseconds=pos))
	time = time.rsplit('.', 1)[0]
	time = time.split(':', 1)[1]
	return time


def get_time_at(prcnt):
	duration = audio.duration()
	if duration == 0:
		return "00:00"
	pos  = duration * prcnt
	pos /= 1000
	time = str(tdelta(microseconds=pos))
	time = time.rsplit('.', 1)[0]
	time = time.split(':', 1)[1]
	return time
