"""mems.instrument.client.tk.chat_frame

Contains the chat user interface.
"""

# created 2002/01/23, AMK

__revision__ = "$Id: chat_frame.py,v 1.3 2002/02/19 22:49:55 akuchlin Exp $"

import string
import Tkinter

class ChatFrame(Tkinter.Frame):
    def __init__ (self,client,*args):
        apply(Tkinter.Frame.__init__,(self,) + args)

        self.client = client
        
	self.chat_messages = Tkinter.Text(self, height=8, width=20)
	self.user_list_field = Tkinter.Text(self, height=8, width=16)
	self.input_field = Tkinter.Entry(self)
        self.input_field.bind('<Return>', self.message_entered)
            
        self.input_field.pack(side=Tkinter.BOTTOM)
        
        self.chat_messages.pack(side=Tkinter.LEFT, expand=1,
                                fill=Tkinter.BOTH)
        s = Tkinter.Scrollbar(self, command=self.chat_messages.yview)
        s.pack(side=Tkinter.LEFT, expand=1, fill=Tkinter.Y)
        self.chat_messages.configure(yscrollcommand=s.set)

        s = Tkinter.Scrollbar(self, command=self.user_list_field.yview)
        s.pack(side=Tkinter.RIGHT, expand=1, fill=Tkinter.Y)
        self.user_list_field.pack(side=Tkinter.RIGHT, fill=Tkinter.Y, expand=1)
        self.user_list_field.configure(yscrollcommand=s.set)
        
    def message_entered (self, event):
	text = self.input_field.get()
        text = string.strip(text) 
        self.input_field.delete('0', 'end')
        
	if text!="":
	    self.client.send_message('CHATMSG msg="%s"' % text)

    def add_message (self, user, message):
        text = "<%s>\n   %s\n" % (string.strip(user), string.strip(message))
        self.chat_messages.insert('end', text)
        
    def update_userlist (self, userlist, controller_id):
        userlist = userlist[:]
        try:
            index = userlist.index(controller_id)
        except ValueError:
            pass
        else:
            userlist[index] = 'CONTROL:' + userlist[index] 

        userlist.sort()
        text = string.join(userlist, "\n")
        self.user_list_field.delete('1.0', 'end')
        self.user_list_field.insert('1.0', text)
        

