# $Id: time2.tcl 1461 2008-06-15 19:45:10Z sergei $
# Replies to XEP-0202 (Entity Time) queries

custom::defvar options(reply_xmpp_time) 1 \
    [::msgcat::mc "Reply to entity time (urn:xmpp:time) requests."] \
    -group IQ -type boolean

proc xmpp_time {connid from lang child} {
    variable options

    if {!$options(reply_xmpp_time)} {
	return {error cancel service-unavailable}
    }

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

    set curtime [clock seconds]
    set restags \
	[list [jlib::wrapper:createtag utc \
		   -chdata [clock format $curtime \
				  -format "%Y-%m-%dT%TZ" -gmt true]] \
	      [jlib::wrapper:createtag tzo \
		   -chdata [timezone_offset]]]
    
    set res [jlib::wrapper:createtag time \
		 -vars {xmlns urn:xmpp:time} \
		 -subtags $restags]
    
    return [list result $res]
}

proc timezone_offset {} {
    set H [clock format 0 -format %H]
    set M [clock format 0 -format %M]
    set S +

    if {$H > 12} {
	set H [expr {24 - $H}]
	set M [expr {60 - $M}]
	set S -
    }

    return $S$H:$M
}

iq::register_handler get time urn:xmpp:time \
    [namespace current]::xmpp_time

