import threading
import os
import subprocess
import gconf

(
	GSTPLAY,
	GNOMEPLAY,
	NOENGINE
) = range(3)

try:
	import gnome
	gnome.sound_init("localhost")
	ENGINE = GNOMEPLAY
	# Disable gnome play, see bug https://bugs.launchpad.net/ubuntu/+bug/153704
	# When the bug will be fixed remember to remove the raise ImportError
	raise ImportError

except ImportError:
	try:
		import gst
		import gobject
		ENGINE = GSTPLAY
	except ImportError:
		ENGINE = NOENGINE

class __GstPlayThread(threading.Thread):
	def __init__(self, ply):
		self.ply = ply
		threading.Thread.__init__(self)
	def run(self):
		self.ply.set_state(gst.STATE_PLAYING)
		def bus_event(bus, message):
			t = message.type
			if t == gst.MESSAGE_EOS:
				self.ply.set_state(gst.STATE_NULL)
			return True
		self.ply.get_bus().add_watch(bus_event)
			

def __gstplay(filename):
	try:
		cwd = os.getcwd()
		location = os.path.join(cwd, filename)
		ply = gst.element_factory_make("playbin", "player")
		ply.set_property("uri", "file://" + location)
		pt = __GstPlayThread(ply)
		pt.start()
	except:
		pass

if ENGINE == GNOMEPLAY:
	def playsnd(filename):
		gnome.sound_play(filename)
elif ENGINE == GSTPLAY:
	playsnd = __gstplay
else:
	def playsnd(filename):
		pass



def invoke_subprocess(cmdline):
	try:
		setsid = getattr(os, 'setsid', None)
		p = subprocess.Popen(cmdline, close_fds = True, preexec_fn = setsid)
	except OSError:
		print "Warning: cannot execute", cmdline
		return False
	return True

def get_default_mail_reader():
	client = gconf.client_get_default()
	cmd  = client.get_string("/desktop/gnome/url-handlers/mailto/command")
	return cmd.split()[0]

def open_mail_reader():
	cmdline = get_default_mail_reader()
	invoke_subprocess(cmdline)

def open_browser(url):
	client = gconf.client_get_default()
	cmd  = client.get_string("/desktop/gnome/applications/browser/exec")
	cmdline = [cmd.split()[0], url]
	invoke_subprocess(cmdline)

if __name__ == "__main__":
	import gtk
	open_browser("http://google.it")
