import XChat
import re
import os
import sys
import pickle

VERSION = 'v0.0.2'

confFile = 'zulk-snd-config'

test_list = ['zulk','andreas']
chan_list = ['#ldream']
sndFile = '/d/behind.wav'

def save():
	try:
		fp = file(confFile,'w')
		pickle.dump(test_list,fp)
		pickle.dump(chan_list,fp)
		pickle.dump(sndFile  ,fp)
		fp.close()
	except:
		print 'error saving config'

def load():	
	if os.path.exists(confFile):
		fp = file(confFile,'r')
		test_list = pickle.load(fp)
		chan_list = pickle.load(fp)
		sndFile   = pickle.load(fp)
		fp.close()

def add(name, sess, args):
	command = args[0]
	print args
	t = ''
	for a in args[1:]:
		t += a + ' '
	word = t[:-1]	
	print word
	if word[0:4] == 'chan':
		chan_list.append(word[5:])
		sess.print_text("Adding " + word[5:] + " to chan list")
	elif word[0:4] == 'test':
		test_list.append(word[5:])
		sess.print_text("Adding " + word[5:] + " to test list")
	save()
	
def rem(name, sess, args):
	command = args[0]
	t = ''
	for a in args[1:]:
		t += a + ' '
	word = t[:-1]	

	if word[0:4] == 'chan':
		chan_list.remove(word[5:])
		sess.print_text("Removing " + word[5:] + " from chan list")
	elif word[0:4] == 'test':
		sess.print_text("Removing " + word[5:] + " from test list")
		test_list.remove(word[5:])
	save()

def listAll(name, sess, args):
	command = args[0]
	t = ''
	for a in args[1:]:
		t += a + ' '
	word = t[:-1]	

	if word == 'chan':
		sess.print_text(str(chan_list))
	elif word == 'test':
		sess.print_text(str(test_list))

def clear(name, sess, args):
	command = args[0]
	t = ''
	for a in args[1:]:
		t += a + ' '
	word = t[:-1]	

	if word == 'chan':
		chan_list = []
	elif word == 'test':
		test_list = []
	save()

def setSound(name, sess, args):
	command = args[0]
	t = ''
	for a in args[1:]:
		t += a + ' '
	word = t[:-1]	

	if os.path.exists(word):
		sndFile = word
		sess.print_text('Changed sound file')
	else:
		sess.print_text('File does not exist')
	save()
	
def play(name, sess, args):
	os.system('/usr/bin/play /e/behind.wav&')
	sess.print_text("Playing sound!")

def content_ignore_handler(name,flags,args):
	serv = args[0].get_server()
	chan = args[1].get_string()
	nick = args[2].get_string()
	msg = args[3].get_string()

	if nick == serv.info()['nick']:
		return

	if chan in chan_list:
		os.system('/usr/bin/play ' + sndFile + '&')
		return

	for test in test_list:
		if re.search(test, msg,re.I):
			os.system('/usr/bin/play ' + sndFile + '&')
			return


xc = XChat.XChat()
xc.register("SoundPlayer", "Plays a sound when someone sais something in the list.")
xc.get_current_session().print_text("SoundPlayer..."+VERSION+" Loaded")
xc.hook_signal("XP_CHANMSG", content_ignore_handler)
xc.hook_signal("XP_PRIVMSG", content_ignore_handler)
xc.hook_command("SND_PLAY", play)
xc.hook_command("SND_ADD", add)
xc.hook_command("SND_REM", rem)
xc.hook_command("SND_LIST", listAll)
xc.hook_command("SND_CLEAR", clear)
xc.hook_command("SND_SET", setSound)
load()
