import xchat
from tfplib.external import mpdclient2

__module_name__ = "pympd-info"
__module_version__ = "0.1"
__module_description__ = "XChat mpd display script"

def FormatSong(song, status):
	Return = ""
	Stopped = "Nothing Currently Playing..."
	Paused = " (Paused)"
	# First Check that the song exists
	if not song:
		Return = Stopped
		return Return
	# Now See if its stopped
	if status["state"] == "stop" or status["state"] == "pause":
		Return = Stopped
		return Return
	# if we got passed that start creating return :D
	try:
		Artist = song['artist']
	except KeyError:
		Artist = "(Unknown)"
	try:
		Title = song['title']
	except KeyError:
		Title = "(Unknown)"
	if Artist == "(Unknown)" and Title == "(Unknown)":
		File = song['file']
		fFile = ""
		ind1 = File.rfind(".")
		ind2 = File.rfind("/")
		if ind2 == -1 or ind1 == -1:
			fFile = File
		elif ind2 > ind1:
			fFile = File
		else:
			fFile = File[ind2+1:ind1]
		Return = fFile
	elif Artist == "(Unknown)" and song["file"][:7] == "http://":
		# Add ShoutCAST checking here
		Return = "%s (%s)" % (Title, song["file"])
	else:
		Return = "%s - %s" % (Artist, Title)
	return Return

def mpd(word, word_eol, userdata):
	c = mpdclient2.connect()
	song = c.currentsong()
	status = c.status()
	if status["state"] != "play":
		print "Nothing Currently Playing"
	else:
		cmd = "me Spams the channel with %s" % FormatSong(song, status)
		xchat.command(cmd)
	return xchat.EAT_ALL

xchat.hook_command("mpd", mpd, help="""/mpd - Display Currently playing song""")
