from Server import Server

class PdServer(Server):
	def __init__(self, inQueue, outQueue, *args, **kwargs):
		Server.__init__(self, *args, **kwargs)
		self.numchans = 0
		self.IDs = {}
		self.inQueue = inQueue
		self.outQueue = outQueue
	
	def Connected(self, channel, addr):
		print "Connection from", addr, channel
		self.outQueue.put(["connected", str(channel.id)])
	
	def MakeNewID(self, what):
		ID = 1
		IDs = self.IDs.keys()
		while ID in IDs:
			ID += 1
		self.IDs[ID] = what
		return ID
	
	def Pump(self):
		Server.Pump(self)
		if self.numchans != len(self.channels):
			print len(self.channels), "channels"
			self.numchans = len(self.channels)
		# send all queued up messages to all clients
		while not self.inQueue.empty():
			send = self.inQueue.get()
			[c.ToClient(send) for c in self.channels]
		# pump the outgoing sockets of channels
		for c in self.channels:
			c.Pump()
	
	# internal callbacks
	
	def FromClient(self, source, data):
		self.outQueue.put([source] + data)
	
	def Remove(self, channel):
		del self.IDs[channel.id]
		Server.Remove(self, channel)
	
	### Public methods ###
	
	def PostMessage(self, data):
		""" Send a Pd message to all connected clients. """
		self.inQueue.put(data)
	
	# this should use the inQueue or it will result in deadlocks
	#def ToClient(self, id, data):
	#	[c.ToClient(["server"] + data) for c in self.channels if int(c.id) == int(id)]:
	
	# check the queue and return any messages from clients
	def GetMessages(self):
		""" Get any pending Pd messages from connected clients. """
		messages = []
		while not self.outQueue.empty():
			messages.append(self.outQueue.get())
		return messages

