# Allows to open history window without using mouse.
# Usage: "/history jid"
# Written by Alex Smirnov <sceptic13@gmail.com>

namespace eval openhistory {

    hook::add generate_completions_hook [namespace current]::roster_compls
    hook::add chat_send_message_hook [namespace current]::handle_command 15
}

proc openhistory::handle_command {chatid user body type} {
    if {[string match {/history*} $body]} {
        set cmd /history
    } else return

    set user [lindex [split $body] 1]
    set connid [::chat::get_xlib $chatid]
    set jid _

    if {![string length $user]} {
        set xlib [::chat::get_xlib $chatid]
        set jid [::xmpp::jid::stripResource [::chat::get_jid $chatid]]
        set groupid [::chat::chatid $xlib $jid]

        if {[::chat::is_groupchat $groupid]} {
            set jid [::chat::get_jid $chatid]
        }
    } elseif {[string first "@" $user] >= 0} {
        set jid $user
    } else {
        set jid [::chat::get_jid $chatid]/$user
    }

    ::logger::show_log $jid -connection $connid
    return stop
}

proc openhistory::roster_compls {chatid compsvar wordstart line} {
    upvar 0 $compsvar comps

    if {!$wordstart} {
        lappend comps {/history }
    }

    if {$wordstart && [string match {/history*} $line]} {
        set prefix $plugins::completion::options(prefix)
        set suffix $plugins::completion::options(suffix)

        set jidcomps {}
        set connid [chat::get_xlib $chatid]

        foreach jid [roster::get_jids $connid] {
            if {[roster::itemconfig $connid $jid -isuser]} {
                lappend jidcomps $prefix$jid$suffix
            }
        }

        set jidcomps [lsort -dictionary -unique $jidcomps]
        set comps [concat $comps $jidcomps]
    }

}

# vim:ft=tcl:ts=8:sw=4:sts=4:et
