# $Id: history.tcl 494 2003-12-18 19:23:40Z aleksey $

proc history_move {chatid shift} {
    variable history

    set newpos [expr $history(pos,$chatid) + $shift]

    if {$newpos < 0} { set newpos 0 }
    set len [expr [llength $history(stack,$chatid)] - 1]

    if {$newpos > $len} { set newpos $len }
	
    set iw [chat::winid $chatid].input
    set body [$iw get 1.0 "end -1 chars"]

    if {$history(pos,$chatid) == 0} {
	set history(stack,$chatid) \
	    [lreplace $history(stack,$chatid) 0 0 $body]
    }


    set history(pos,$chatid) $newpos

    set newbody [lindex $history(stack,$chatid) $newpos]

    $iw delete 1.0 end
    after idle [list $iw insert end $newbody]
}

#debugmsg plugins "HISTORY: [namespace which history_move]"
#namespace export history_move

proc add_body_to_history {chatid user body type} {
    variable history

    lvarpush history(stack,$chatid) $body 1
    set history(pos,$chatid) 0

}
hook::add chat_send_message_hook [namespace current]::add_body_to_history 12


proc setup_history_bindings {chatid type} {
    variable history

    set cw [chat::winid $chatid]

    bind $cw.input <Control-Key-Up> \
	[list [namespace current]::history_move [double% $chatid] 1]
    bind $cw.input <Control-Key-p> \
	[list [namespace current]::history_move [double% $chatid] 1]
    bind $cw.input <Control-Key-Down> \
	[list [namespace current]::history_move [double% $chatid] -1]
    bind $cw.input <Control-Key-n> \
	[list [namespace current]::history_move [double% $chatid] -1]

    set history(stack,$chatid) [list {}]
    set history(pos,$chatid) 0
}

hook::add open_chat_post_hook [namespace current]::setup_history_bindings

