#
# $Source: /home/nlfm/Zircon/plugins/Dcc/RCS/chat.tcl,v $
# $Date: 1998/09/02 12:57:38 $
# $Revision: 1.18.1.11 $
#
package provide Dcc 1.18
#
proc closeChat {cht who conn} {
    catch {fileevent $conn readable {} ; close $conn}
    upvar #0 $conn chdata
    if {[info exists chdata]} {
	$chdata(who) deref
	unset chdata
    }
    switch {} [info proc $cht] {} default {
	$cht addText $who "*** $who has closed the connection"
    }
}
#
proc dccChat {mode conn} {
    upvar #0 $conn chdata
    set who [$chdata(who) name]
    set cht $chdata(obj)
    switch $mode {
    r   {
	    if {[catch {gets $conn} buffer] || 
	      ([string match {} $buffer] && [eof $conn])} {
		closeChat $cht $who $conn
	    } {
		regsub -all "\r" $buffer {} buffer
		if {[regexp "(\[^\001\]*)\001\[ \t\]*(\[^ \t\001\]+)\[ \t\]*(\[^\001\]*)\001(\[^\001\]*)" $buffer sub a op cp b]} {
		    set value [handleCTCP [$cht net] $op $cht Chat [$cht caller] {} {} $cp]
		    switch {} $value return
		    set buffer $a$value$b
		}
		handleOn [$chdata(who) net] DCC_CHAT [list $who $buffer]
		$cht addText $who "=$who= $buffer"
		doPatterns $cht $who![$chdata(who) id] $buffer
	    }
	}
    e   {  [$chData(who) net] errmsg "Error on DCC Chat connection with $who" }
    }
}
#
proc user_unChServ {this} {
    upvar #0 AChat[$this net] AChat
    if {[info exist AChat($this)]} {
	safeUnset $AChat($this)
	catch {close $AChat($this)}
	unset AChat($this)
    }
}
#
proc user_unChat {this} {
    $this unChServ
    switch nil [set id [Chat :: find [$this name] [$this net]]] {} default {
	catch {$id delete}
    }
}
