#!/usr/bin/env python
"Connects to JockeTFs MultiPrint server"

#    MultiPrint client, A simple chat client.
#    Copyright (C) 2008  Joakim Soderlund
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import time
import socket

try:
	import readline
except:
	pass

from threading import Thread

__author__ = "Joakim Soderlund"
__version__ = "0.4"
__date__ = "2008-07-28"
__license__ = "GPLv3"
__copyright__ = "Copyright (C) 2008  Joakim Soderlund"

HOST =     "furver.se"
PORT =      50012
PROTOCOL = "3"

def connect(nickname):
	"Connects to the server."
	dataDict = {}
	dataDict["nickname"] = nickname
	dataDict["protocol"] = PROTOCOL
	dataString = ""
	for (k, v) in dataDict.items():
		dataString += k + "=" + v + ":"
	dataString = dataString[:-1]
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
		s.connect((HOST, PORT))
		time.sleep(1)
		s.send(dataString)
		return s
	except:
		print("Connection to %s:%s failed." % (HOST, PORT))
		sys.exit()

class reciever(Thread):
	"Recives data from the server."
	def __init__(self, socket):
		Thread.__init__(self)
		self.socket = socket
	def run(self):
		try:
			while True:
				data = self.socket.recv(4096)
				if not data: break
				print(data)
		except:
			pass
		socket.close()
		print("Connection terminated successfully.")

def sender(socket):
	"Sends data to the server."
	while True:
		try:
			message = raw_input()
			socket.send(message)
			if message == "/quit":
				return
			if not message: 
				return
		except (KeyboardInterrupt, EOFError):
			print " >>> Type /quit to exit! <<<"
			pass
		except:
			return

if __name__ == "__main__":
	nickname = raw_input("Nickname: ")
	socket = connect(nickname)
	pt = reciever(socket)
	pt.start()
	sender(socket)

