#!/usr/bin/env python
"Multiprint curses client."

#    Multiprint client curses, connects to a multiprint server.
#    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 mpclient
import curses
import time

from threading import Thread

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

HOST =      mpclient.HOST
PORT =      mpclient.PORT
PROTOCOL = "3"

class reciever(Thread):
	def __init__(self, socket):
		Thread.__init__(self)
		self.socket = socket

	def run(self):
		try:
			data = self.socket.recv(4096)
			outWin.addstr(data)
			outWin.refresh()
			while True:
				data = self.socket.recv(4096)
				if not data: break
				outWin.addch(10)
				outWin.addstr(data)
				outWin.refresh()
		except:
			pass
		self.socket.close()

def sender(socket):
	chars = ""
	try:
		while True:
			stdscr.refresh()
			char = inWin.getch()
			if char == 10:
				inWin.erase()
				inWin.refresh()
				socket.send(chars)
				if chars == "/quit":
					break
				chars = ""
			elif char == 127:
				try:
					chars = chars[:-1]
					inWin.clear()
					inWin.addstr(chars)
					inWin.refresh()
				except IndexError:
					pass
			elif char > 256 or char < 0:
				pass
			else:
				chars += chr(char)
				inWin.addch(char)
				inWin.refresh()
	except:
		pass

	try:
		socket.close()
	except:
		pass
	curses.nocbreak()
	stdscr.keypad(0)
	curses.echo()
	curses.endwin()

if __name__ == "__main__":
	try:
		if PROTOCOL != mpclient.PROTOCOL:
			raise Exception("Version missmatch!")
		stdscr = curses.initscr()
		curses.echo()
		curses.cbreak()
		stdscr.keypad(True)
		curses.curs_set(0)
		outWin = curses.newwin(23, 80, 0, 0)
		outWin.scrollok(True)
		inWin = curses.newwin(1, 80, 23, 0)
		inWin.scrollok(True)
		inWin.addstr("Nickname: ")
		stdscr.refresh()
		nickname = inWin.getstr()
		inWin.clear()
		stdscr.refresh()
		curses.noecho()
		socket = mpclient.connect(nickname)
		pt = reciever(socket)
		pt.start()
		sender(socket)
	except:
		raise
	try:
		socket.close()
	except:
		pass
	curses.curs_set(1)
	curses.nocbreak()
	stdscr.keypad(0)
	curses.echo()
	curses.endwin()

