# $Id: log_on_open.tcl 1560 2008-10-19 06:23:58Z sergei $

namespace eval log_on_open {
    custom::defvar options(max_messages) 20 \
	[::msgcat::mc "Maximum number of log messages to show in newly\
		       opened chat window (if set to negative then the\
		       number is unlimited)."] \
	-type integer -group Chat
    custom::defvar options(max_interval) 24 \
	[::msgcat::mc "Maximum interval length in hours for which log\
		       messages should be shown in newly opened chat\
		       window (if set to negative then the interval is\
		       unlimited)."] \
	-type integer -group Chat
}

proc log_on_open::show {chatid type} {
    variable options

    if {$type != "chat"} return

    set xlib [chat::get_xlib $chatid]
    set jid [chat::get_jid $chatid]
    set bare_jid [::xmpp::jid::stripResource $jid]
    set gc [chat::is_groupchat [chat::chatid $xlib $bare_jid]]

    if {!$gc} {
	set log_jid $bare_jid
    } else {
	set log_jid $jid
    }
    
    set messages [::logger::get_last_messages $log_jid $options(max_messages) \
					      $options(max_interval)]

    foreach msg $messages {
	array unset tmp
	if {[catch {array set tmp $msg}]} continue

	set x {}
	if {[info exists tmp(timestamp)]} {
	    set seconds [clock scan $tmp(timestamp) -gmt 1]
	    lappend x [::xmpp::delay::create $seconds]
	}
	if {[info exists tmp(jid)]} {
	    if {$tmp(jid) == ""} {
		# Synthesized message
		set from ""
	    } elseif {(!$gc && [::xmpp::jid::stripResource $tmp(jid)] != $bare_jid) || \
		 $gc && $tmp(jid) != $jid} {
		set from [connection_jid $xlib]
	    } else {
		set from $jid
	    }
	} else {
	    set from ""
	}
	# Don't log this message. Request this by creating very special 'empty'
	# tag which can't be received from the peer.
	# TODO: Create more elegant mechanism
	lappend x [::xmpp::xml::create "" -xmlns tkabber:x:nolog]

	chat::add_message $chatid $from $type $tmp(body) $x
    }
}

hook::add open_chat_post_hook [namespace current]::log_on_open::show 100

# vim:ts=8:sw=4:sts=4:noet
