# $Id: fetch_nicknames.tcl 1024 2007-03-07 15:58:27Z sergei $
# Fetch roster item nickname(s) from vCard and set roster label(s)

namespace eval fetch_nickname {}

proc fetch_nickname::service_request {connid service} {
    foreach jid [::roster::get_jids $connid] {
	if {[server_from_jid $jid] == [server_from_jid $service]} {
	    user_request $connid $jid
	}
    }
}

proc fetch_nickname::request_group_nicks {connid group args} {
    foreach jid [eval [list ::roster::get_group_jids $connid $group] $args] {
	if {[string equal [::roster::itemconfig $connid $jid -category] user]} {
	    user_request $connid $jid
	}
    }
}

proc fetch_nickname::user_request {connid jid} {
    jlib::send_iq get \
	[jlib::wrapper:createtag vCard \
	     -vars [list xmlns vcard-temp]] \
	-to $jid \
	-connection $connid \
	-command [list [namespace current]::parse_result $connid $jid]
}

proc fetch_nickname::parse_result {connid jid res child} {
    if {$res != "OK"} return

    jlib::wrapper:splitxml $child tag vars isempty chdata children

    foreach item $children {
	userinfo::parse_vcard_item $jid $item
    }

    if {[info exists ::userinfo::userinfo(nickname,$jid)] && \
	    ![cequal $::userinfo::userinfo(nickname,$jid) ""]} {
	roster::itemconfig $connid $jid \
			   -name $::userinfo::userinfo(nickname,$jid)
	roster::send_item $connid $jid
    }
}

proc fetch_nickname::extend_user_menu {m connid jid} {
    set rjid [roster::find_jid $connid $jid]
    if {$rjid == ""} {
	set state disabled
    } else {
	set state normal
    }
    $m add command -label [::msgcat::mc "Fetch nickname"] \
	-command [list [namespace current]::user_request $connid $rjid] \
	-state $state
}

hook::add chat_create_user_menu_hook \
    [namespace current]::fetch_nickname::extend_user_menu 73
hook::add roster_jid_popup_menu_hook \
    [namespace current]::fetch_nickname::extend_user_menu 73

proc fetch_nickname::extend_service_menu {m connid jid} {
    set rjid [roster::find_jid $connid $jid]
    if {$rjid == ""} {
	set state disabled
    } else {
	set state normal
    }
    $m add command -label [::msgcat::mc "Fetch user nicknames"] \
	-command [list [namespace current]::service_request $connid $rjid] \
	-state $state
}

hook::add roster_service_popup_menu_hook \
    [namespace current]::fetch_nickname::extend_service_menu 73

proc fetch_nickname::extend_group_menu {m connid name} {
    variable ::ifacetk::roster::options
    $m add command \
	-label [::msgcat::mc "Fetch nicknames of all users in group"] \
	-command [list [namespace current]::request_group_nicks $connid $name \
	    -nested $options(nested) \
	    -delimiter $options(nested_delimiter)]
}

hook::add roster_group_popup_menu_hook \
    [namespace current]::fetch_nickname::extend_group_menu

