# -*- coding: utf8 -*-
import os, sys

__module_name__		= "X-Chat MPD_Info Script"
__module_version__	= "0.4.9"
__module_description__	= "Prints Music Player Demon info"
__module_author__	= "Michael Edwards <eddy@lug-norderstedt.de>, heavily edited by skaven & nadar @ irc://irc.spotchat.org/winfuture (sic!) ^^ or mail skaven on skav3n de / thenadar on gmx net"

# This is the MPD_Info Script, written by Eddy
# a lot of additional works by skaven and nadar (more or less a rewrite (; )
#
#  # # _R_E_Q_U_I_R_E_S_:   mpd, mpc and python # # # 
#
#
# Features:
# You can display the current song or the current radio  stream.
# The script detects if it is a song or a stream and toggles the output
# of mpd.
#
# todo: some better regexp at "path" (if one wants to use the path for further file operations) and the path for "dcc", because some strange signs in the pathname produce an error:
# can't access /foopath to a /subfolder with/ some special !!!  characters/blahfoo.ogg
# file or folder not found
# if somebody fixes this, a feedback to nadar would be very nice :)
#
# commands:
# np		: displays current song/stream information in to the current channel
# mpd np	: displays current song/stream information in to the current channel
# mpd stats	: displays the stats of the mpd server in the current channel
# mpd local	: prints song information for you
# mpd play	: toggles between play and pause
# mpd pause	: pauses mpd playback
# mpd stop	: stops mpd playback
# mpd next	: plays next song, and jumps to the beginning of the list if the end is reached
# mpd prev	: plays previous song
# mpd vol	: displays or changes volume level of mpd
# mpd dcc	: sends current song over DCC
# mpd path	: shows the path to the current playing song
# mpd version	: displays script version information in to the current channel
#
# DON'T TOUCH THE CODE BELOW, UNLESS YOU KNOW WHAT YOU'RE DOING!
#
import xchat
import commands

def	mpd(word, word_eol, userdata):

	if len(word) > 1:
# Channel announcing #
		if word[1] == "np":
			notitle = commands.getoutput("mpc | wc -l")
			notag = commands.getoutput("mpc --format  '[%artist% - %title%]'| head -n1 | wc -m")
			stream = commands.getoutput("mpc --format '%file%' | grep http:// | wc -l")
			streamtitle = commands.getoutput("mpc --format  '[%title% (%name%)]' | head -n1")
			url = commands.getoutput("mpc --format '%file%' | head -n1")
			artist = commands.getoutput("mpc --format  '[%artist%]' | head -n 1 | sed 's/ - $//;s/^ - //'")
			track = commands.getoutput("mpc --format  '[%track%]' | head -n 1 | sed 's/ - $//;s/^ - //'")
			title = commands.getoutput("mpc --format  '[%title%]' | head -n 1 | sed 's/ - $//;s/^ - //'")
			album = commands.getoutput("mpc --format  '[%album%]' | head -n 1 | sed 's/ - $//;s/^ - //'")
			file = commands.getoutput("mpc --format  '[%file%]' | head -n 1 | sed -r 's/.{2,4}$//g;s/^.*\///g'")
			paused = commands.getoutput("mpc | tr ' ' '\012 ' | grep paused")
			timetot = commands.getoutput("mpc --format '[%time%]' | head -n1")
			timeof = commands.getoutput("mpc | grep ^'\[p.*]' | tr ' ' '\012 ' | grep :")
			advance = commands.getoutput("mpc | grep ^'\[p.*]' | tr ' ' '\012 '| sed -e 's/(//' -e 's/)//' | grep %")
			volume = commands.getoutput("mpc volume | sed 's/://g' | sed 's/v/V/g' | sed 's/%/ %/g' | sed 's/e1/e 1/g' | cut -c -11")
			if notitle == "1": xchat.command("me ♬ nothing")	
			else:
				if stream == "1": xchat.command("me ♬ %s - %s %s (%s %s) %s" % (streamtitle, url, timeof, advance, volume, paused))
				else:
					if notag == "1": xchat.command("me ♬ %s %s (%s %s) %s" % (file, timeof, advance, volume, paused))
# * # * If you want to change the now-playing output, most likely you should play with the line below (:
					else: title = xchat.command("me ♬ %s - %s %s - %s (%s %s) %s %s" % (artist, track, title, album, timeof, advance, volume, paused))
# Announce the filename (without extension)						
		elif word[1] == "file":
			file = commands.getoutput("mpc --format  '[%file%]' | head -n 1 | sed -r 's/.{2,4}$//g;s/^.*\///g'")
			xchat.command("me ♬ %s an" % (file))			
# Local announcing #
		elif word[1] == "local":
			title = commands.getoutput("mpc | head -n 1")
			print("Your're listening to %s" % title)
# Stats announcing #
		elif word[1] == "stats":
			title = commands.getoutput("mpc stats | sed '/^$/d; s/^/ ][ /'  |  tr -d '\n'| sed 's/$/ ]/g; s/ ]//'")
			xchat.command("me Music Player Daemon Status: %s" % title)
# Play/Pause toggle #
		elif word[1] == "play":
			playing = commands.getoutput("mpc | grep playing | wc -l")
			title = commands.getoutput("mpc | head -n 1")
			play = commands.getoutput("mpc play | head -n 1")
			if playing == "0": print("mpd starts playing: %s" % play)
			else: 
				commands.getoutput("mpc pause") 
				print("mpd is paused")
# Stop #
		elif word[1] == "stop":
			commands.getoutput("mpc stop")
			print("mpd stops playing")
# Next #
		elif word[1] == "next":
			commands.getoutput("mpc next")
			notitle = commands.getoutput("mpc | wc -l")
			play = commands.getoutput("mpc | head -n 1")
			if notitle == "1": commands.getoutput("mpc play")
			print(">> %s" % play)
# Previous #
		elif word[1] == "prev":
			commands.getoutput("mpc prev")
			notitle = commands.getoutput("mpc | wc -l")
			play = commands.getoutput("mpc | head -n 1")
			if notitle == "1": commands.getoutput("mpc play")
			print("<< %s" % play)
# Volume #
		elif word[1] == "vol":
			if len(word) > 2:
				vol = word[2]
				commands.getoutput("mpc volume %s" % vol)
				volnow = commands.getoutput("mpc volume | awk {'print $2'} | grep '%'")
			else: volnow = commands.getoutput("mpc volume | awk {'print $2'}")
			print("Volume is set to %s" % volnow)
# DCC #
		elif word[1] == "dcc":
			path = commands.getoutput("echo $(cat ~/.mpdconf | grep music_directory | sed -r 's/\"//g' | awk {'print $2'})$(mpc --format  '/%file%' | head -n 1)")
			notitle = commands.getoutput("mpc | wc -l")
			if len(word) > 2:
				user = word[2]
				if notitle == "1": print("mpd is not playing")	
				else: title = xchat.command("dcc send %s \"%s\"" % (user, path))
			else: title = xchat.command("help mpd")
# Path
		elif word[1] == "path":
			path = commands.getoutput("echo $(cat ~/.mpdconf | grep music_directory | sed -r 's/\"//g' | awk {'print $2'})$(mpc --format  '/%file%' | head -n 1)")
			stream = commands.getoutput("mpc --format '%file%' | grep http:// | wc -l")
			streamurl = commands.getoutput("mpc --format  '[%file%]' | head -n 1")
			notitle = commands.getoutput("mpc | wc -l")
			if notitle == "1": print("mpd is not playing")
			else:
				if stream == "1": print("mpd plays: %s" % streamurl)
				else: 
					print("mpd plays: %s" % path)
		elif word[1] == "version":
			xchat.command("me is using X-Chat2 mpd script [0.4.9] by Eddy, nadar and skaven")
		else: title = xchat.command("help mpd")
	else: title = xchat.command("help mpd")
	return xchat.EAT_ALL

xchat.hook_command("mpd", mpd, help="Usage:\nMPD NP, announces currently playing song to the active channel\nMPD FILE, announces filename of the currently playing song to the active channel\nMPD LOCAL, prints currently playing song locally in the active window\nMPD STATS, announces mpd statistics to the active channel\nMPD PLAY, starts and pauses the mpd playback\nMPD STOP, stops the mpd playback\nMPD NEXT, plays the next song in the mpd playlist\nMPD PREV, plays the previous song in the mpd playlist\nMPD VOL <[-/+]value>, displays the volume or changes it to <value> or by <-/+value>\nMPD DCC <nick>, sends currently playing song to someone over DCC \nMPD PATH prints the path/to/file currently playing or the url of the stream\nMPD VERSION, announces the version of the script to the currently active channel")

def	np(word, word_eol, userdata):
	xchat.command("mpd np")
	return xchat.EAT_ALL
xchat.hook_command("np", np, help="Usage: np, announces currently playing song to the active channel")



print	"X-Chat2 mpd script [0.4.9] by Eddy, nadar and skaven loaded"

# changes: 
# 0.4.9 added UTF-8 encoding like recommended in http://www.python.org/dev/peps/pep-0263/
# 0.4.9 added "[paused]"
# 0.4.7 fixed a bug which appeared when a stream with no tag was played