#!/usr/bin/python
# Copyright (c) 2002 Sean R. Lynch <seanl@chaosring.org>
#
# This file is part of PythonVerse.
#
# PythonVerse 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 2 of the License, or
# (at your option) any later version.
# 
# PythonVerse 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 PythonVerse; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# -*-Python-*-

import sys, os, string, re, asyncore, expect, time
import OpenVerse, client

class BotClient(client.Client):
    def __init__(self, nick, pipe):
        self.nick = nick
        self.pipe = pipe
        
    def chat(self, nick, s):
        global USER
        if self.pipe is None: return
        if nick == self.nick: return
        m = re.match(self.nick + '[,:; ]*(.+)', s)
        if m: 
            USER = nick
            s = m.group(1)
        
        try: self.pipe.write(s + '\n\n')
        except: 
            print "Couldn't write"
            self.pipe = None        

def main(argv, env):
    global USER
    
    USER = None
    
    nick = argv[1]
    host = argv[2]
    port = int(argv[3])
    avatar = argv[4]
    command = string.join(argv[5:])

    # Open a pipe to the command    
    pipe = expect.popen(command, 'b')
    c = BotClient(nick, pipe)
    server = OpenVerse.ServerConnection(host, port, c, nick, avatar)
    c.set_server(server)
    #asyncore.poll(5)
    #asyncore.poll(5)
    #server.chat('Lah hello')
    while 1:
        asyncore.poll(5)
        try:
            data = string.strip(c.pipe.read())
            print data
        except: 
            print 'crashed'
            pipe = expect.popen(command, 'b')
            c.pipe = pipe
        else:
            #print >> sys.stderr, data
            if data and USER:
                for line in string.split(data, '\n'):
                    server.chat('%s: %s' % (USER, line))
            
                USER = None

if __name__ == '__main__':
    main(sys.argv, os.environ)

