import socket, select, sys, subprocess, time
from subprocess import Popen
#port = 1254

def getsocket(port):
	s = socket.socket()
	s.connect(("localhost", port))
	return s

from conv import conv

def sorter(peer1, peer2):
	peer1 = int( peer1.split("_")[1] )
	peer2 = int( peer2.split("_")[1] )
	return cmp(peer1, peer2)
	
def getstdout(cmd):
	p=Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
	p.wait()
	output = p.stdout.read()
	return output

def getport():
	sock = getsocket(6968)
	line = sock.recv(1024)
	portnum = line.split(" ")[0]
	return int(portnum)
def talk(sock):
	mine = filter((lambda x: x.startswith("peer0")), conv.keys())
	other = filter((lambda x: x.startswith("peer1")), conv.keys())
	mine.sort(sorter)
	other.sort(sorter)
	for i in mine:
		print "Messages: %s and %s" % (i, other[0])
		sock.send(conv[i])
		print "Sent: %s" % (repr(i))
		while True:
			r,w,e = select.select([sock], [], [])
			if len(r) == 1:
				out = sock.recv(1024)
				print "Got: %s" % (repr(out))
				expected = conv[other.pop(0)]
				print "Expected: %s" % (repr(expected))
				break

	
if __name__=="__main__":
	port = getport()
	print "Connecting to novacom, running on port: %s" % (port)
	sock = getsocket(port)
	talk(sock)
