#!/usr/bin/env python
__module_name__ = "mpd display"
__module_version__ = "0.3.2"
__module_description__ = "mpd display"
__module_author__ = "Kuznetsov Ilya <worklez at treblefrei dot org>"

# thx 2 ripper for bugreport

import xchat
import os
import socket
import re

def show_song(word, word_eol, userdata):

	# the keys may vary on your mpd configuration and/or version.
	# you may look at available for your keys by typing 
	# $ echo -en 'currentsong\\nclose\\n' | netcat $MPD_HOST $MPD_PORT
	
	whatineed = "Artist,Title,Genre,Date,Album,Time".split(",")
	
	ineed = {}
	ineed["ENABLED"] = 1
	ineed["volume"] = 0
	ineed["repeat"]	= 0
	ineed["playlist"] = 0
	ineed["playlistlength"] = 0
	ineed["xfade"] = 0
	ineed["state"] = 0
	ineed["time"] = 1
	ineed["bitrate"] = 0
	ineed["audio"] = 0
	
	mpdhostname = "MPD_HOST" in os.environ.keys() and os.environ["MPD_HOST"] or "127.0.0.1"
	mpdport = "MPD_PORT" in os.environ.keys() and int(os.environ["MPD_PORT"]) or 6600

	def fixzero (str):
		return len (str) < 2 and "0" + str or str

	s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
	s.connect ((mpdhostname, mpdport))
	s.send ("currentsong\n")
	
	data = ''
	c = s.recv(1)
	while c != "\n":
		data += c
		c = s.recv (1)

	p = re.compile(".*MPD (.*)$")
	mpd_version = p.sub ("\\1", data)
	data = ''
	
	while "OK" not in data:
		data += s.recv(1)
	
	data = data.split("\n")
	p = {}
	result = {}
	for line in whatineed:
		p[line] = re.compile(line + ": (.*)")
		
	for line in data:
		for i in p:
			if (p[i].search(line)):
				result[i] = p[i].sub ("\\1", line)
	
	if ineed["ENABLED"]:
		s.send ("status\n")
		data = ''
		while "OK" not in data:
			data += s.recv(1)
	
		data = data.split("\n")
		p = {}
		result2 = {}

		for line in ineed.keys():
			if line != "ENABLED" and ineed[line]:
				p[line] = re.compile(line+": (.*)")

		for line in data:
			for i in p:
				if p[i].search(line):
					result2[i] = p[i].sub ("\\1", line)

		if (ineed["time"]):
			p = re.compile("(\d*):\d*")
			result["ElapsedTime"] = p.sub("\\1", result2["time"])
			minutes = str(int(result["ElapsedTime"])/60)
			seconds = fixzero(str(int(result["ElapsedTime"])%60))
			result["ElapsedTime"] = minutes + ":" + seconds

		if ineed["audio"]:
			p = re.compile("(\d*):\d*:\d*")
			result["Hz"] = p.sub("\\1", result2["audio"])
			p = re.compile("\d*:\d*:(\d*)")
			result["Channels"] = p.sub("\\1", result2["audio"])

		for line in whatineed:
			if line not in result.keys():
				result[line] = "";

	s.send("close\n")
	s.close()

	def wall():
		return ''

	def lightadd():
		return '11,1'+ wall()
	
	def darkadd():
		return '10,1'+wall()
	
	def quoteadd():
		return darkadd() + '-'
	
	def defadd():
		return '15,1'+ wall()
	
	def getinfod(info):
	  	return result[info]
	
	def extinfo(info):
		return getinfod(info) and '->' + lightadd() + getinfod(info) + darkadd() + '<- ' or ''

	prefix = 'me ' + darkadd()
	postfix = darkadd() + '->' + lightadd() + 'music player daemon ' + mpd_version + darkadd() + '<-'
	isplaying = quoteadd() + '>' + defadd() + wall() + getinfod('Artist') +  darkadd() + ' - ' + defadd() + wall() + getinfod('Title') + darkadd() + '<' + quoteadd() + ' '
	seconds = fixzero(str(int(getinfod("Time"))%60))
	other = extinfo('Album') + extinfo('Genre') + extinfo('Date') + darkadd() + '->' + lightadd() + getinfod("ElapsedTime") + darkadd() + '/' + lightadd() + str(int(getinfod("Time"))/60) + ":" + seconds + darkadd() + '<- '
	songdata = prefix + isplaying + other + postfix

	xchat.command(songdata)
	return xchat.EAT_ALL

xchat.hook_command("mpd", show_song)
print 'Music Media Player now playing loaded, usage: "/mpd"'
