#!/usr/bin/python
from wxPython.wx import *
from myrevents import *
from socket import *
from threading import Thread
import sys, string

class Irc(Thread):
	def __init__(self, parent, host, port, channels, name):
		Thread.__init__(self)
		self.parent = parent
		name = name.replace(" ", "_")
		self.name = name
		self.channels = channels
		self.port = port
		self.host = host
		self.running = 1

	def shutdown(self):
		self.sock.send("QUIT\n\r")
		self.running = 0

	def run(self):
		#Open a socket to the server
		try:
			self.sock = socket(AF_INET, SOCK_STREAM)
			self.sock.connect((self.host, self.port))
		except:
			print "Couldn't connect to IRC server."
			return 1
			
		#IRC initialization
		self.sock.send("USER " + self.name + " 0 * :" + self.name +"\n\r")
		self.sock.send("NICK " + self.name + "\n\r")
		for channel in self.channels:
			self.sock.send("JOIN " + channel + "\n\r")
		
		while self.running:
			data = self.sock.recv(1024)
			print data
			if data[:4] == "PING":
				pongid = data[5:]
				self.sock.send("PONG " + pongid +"\n\r")
				continue
			try:
				data = data.replace("\n", "")
				data = data.replace("\r", "")
				userstring, type, channel, speech = string.split(data[1:], " ", 3)
				username, host = string.split(userstring, "!", 1)
				speech = speech[1:] # strip ':'
			except:
				continue #Uninteresting data
			if channel == self.name and speech[:8] == "\001VERSION":
				self.sock.send("NOTICE " + username + " :\001VERSION Myrmidia Client 0.10\001\n\r")
				continue
			wxPostEvent(self.parent, SayEvent(username + "|IRC" + "|" + speech))
		self.sock.close()	

	def say(self, channel, string):
		self.sock.send("PRIVMSG " + channel +" :" + string + "\n\r")


