# Bryan Schumake (8/7/2010)

import gst
import datetime
import threading
import pipeline
from libsaria import callbacks
from libsaria import prefs
from libsaria import controls

timedelta    = datetime.timedelta
audio_lock   = threading.Lock()
lock_audio   = audio_lock.acquire
unlock_audio = audio_lock.release

def shutdown():
	lock_audio()
	pipeline.reset()
	unlock_audio()

def load_file(file):
	lock_audio()
	pipeline.load_file("file", file)
	unlock_audio()
	callbacks.load_file(file)

def get_cur_file():
	lock_audio()
	file = pipeline.get_cur_file()
	unlock_audio()
	return file

def get_state():
	lock_audio()
	state = pipeline.get_state()
	unlock_audio()
	return state

def is_playing():
	return get_state() == gst.STATE_PLAYING

def do_notify_playing():
	if get_state() == gst.STATE_PLAYING:
		callbacks.play()

def play():
	lock_audio()
	pipeline.play()
	unlock_audio()
	do_notify_playing()

def do_notify_paused():
	if get_state() == gst.STATE_PAUSED:
		callbacks.pause()

def pause():
	lock_audio()
	pipeline.pause()
	unlock_audio()
	do_notify_paused()

def stop():
	lock_audio()
	pipeline.stop()
	unlock_audio()
	do_notify_paused()

def seek(amount):
	lock_audio()
	pipeline.seek(amount)
	unlock_audio()

def seek_prcnt(prcnt):
	lock_audio()
	pipeline.seek_prcnt(prcnt)
	unlock_audio()

def set_volume(prcnt):
	lock_audio()
	pipeline.set_volume(prcnt)
	unlock_audio()
	prefs.set("libsaria.audio.volume", prcnt)
set_volume(prefs.init("libsaria.audio.volume", 1.0))

def position():
	lock_audio()
	pos = pipeline.position()
	unlock_audio()
	return pos

def duration():
	lock_audio()
	dur = pipeline.duration()
	unlock_audio()
	return dur

def make_progstr(spot):
	sec = spot / 1000000000
	lenstr = "%s" % timedelta(seconds=sec)
	if lenstr[0] == "0" and lenstr[1] == ":":
		lenstr = lenstr[2:]
	else:
		lenstr = lenstr
	return lenstr.split(".")[0]

def get_progstr():
	return make_progstr(position())

def get_time_at(prcnt):
	return make_progstr(duration() * prcnt)

def get_progress():
	dur = duration()
	if dur > 0.0:
		return position() / dur
	return 0.0

def bus_message(bus, message):
	if message.type == gst.MESSAGE_EOS:
		controls.catch_eos()
pipeline.bus.connect("message", bus_message)
