#! /usr/bin/python

##
## clirc -- An IRC client in Python.
##
## Copyleft 1997 Teemu Kalvas <chery@s2.org>
##

## +class P
##  -method quit
##  -method wait
##  -method screen
##  -method servers
##  -method reload

import select
import string
import sys
import time
import traceback

import editfield
import screen
import server
import statline
import user
import window

dir = sys.argv[0][:string.rfind(sys.argv[0], '/')]
if len(dir) >= 3 and dir[-3:] == 'bin':
    dir = dir[:-3] + 'lib/clirc'
sys.path.insert(0, dir)

import config

class P:
    pass

p = P()

config.init(p)
p.quit = 0
p.wait = []
p.screen = screen.Screen()

try:
    p.servers = [user.User()]
    for serv in p.want_servers:
	srv = server.Server(p, serv)
	if srv.connected:
	    p.servers.append(srv)

    while not p.quit:
	config.do(p)
	p.reload = 0
	while not p.reload and not p.quit:
	    if p.screen.touched:
		p.screen.edit_area.move(0, p.screen.edit_field.position -
					p.screen.edit_field.offset)
		##p.screen.window.touchwin()
		if p.screen.touched & 1:
		    p.screen.log_area.touchwin()
		    p.screen.log_area.refresh()
		if p.screen.touched & 2:
		    p.screen.stat_area.touchwin()
		    p.screen.stat_area.refresh()
		p.screen.edit_area.touchwin()
		p.screen.edit_area.refresh()
		p.screen.touched = 0
	    rl = map(lambda x: x.sock, p.servers)
	    sl = filter(lambda x: len(x.out) > 0, p.servers)
	    wl = map(lambda x: x.sock, sl)
	    if len(p.wait) > 0:
		timeout = max(p.wait[0].time - time.time(), 0.0)
	    else:
		timeout = 3600.0
	    rr, wr = select.select(rl, wl, [], timeout)[:2]
	    if len(rr) > 0:
		for serv in p.servers:
		    if serv.sock == rr[0]:
			serv.read(p)
			del rr[0]
			if len(rr) == 0:
			    break
	    elif len(wr) > 0:
		for serv in p.servers:
		    if serv.sock == wr[0]:
			serv.write(p)
			del wr[0]
			if len(wr) == 0:
			    break
	    while len(p.wait) > 0 and p.wait[0].time <= time.time():
		p.wait[0].eval(p)
		del p.wait[0]
	## load new code
	reload(editfield)
	reload(screen)
	reload(server)
	reload(statline)
	reload(user)
	reload(window)
	reload(config)
	## fix existing class objects
	def fix(old, new):
	    for attr in new.__dict__.keys():
		old.__dict__[attr] = new.__dict__[attr]
	fix(p.servers[0].__class__, user.User)
	if len(p.servers) > 1:
	    fix(p.servers[1].__class__, server.Server)
	fix(p.screen.__class__, screen.Screen)
	fix(p.screen.edit_field.__class__, editfield.EditField)
	fix(p.screen.stat_line.__class__, statline.StatLine)
	fix(p.screen.current.__class__, window.Window)
except:
    dump = sys.exc_type, sys.exc_value, sys.exc_traceback
    screen.clean()
    traceback.print_exception(dump[0], dump[1], dump[2])
else:
    screen.clean()

## End. ##
