# $Id: time.tcl 1520 2008-10-17 17:16:09Z sergei $

custom::defvar options(reply_iq_time) 1 \
    [::msgcat::mc "Reply to current time (jabber:iq:time) requests."] \
    -group IQ -type boolean

proc iq_time {xlib from child args} {
    variable options

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

    set curtime [clock seconds]
    set restags \
	[list [::xmpp::xml::create utc \
		    -cdata [clock format $curtime \
				    -format "%Y%m%dT%T" -gmt true]] \
	     [::xmpp::xml::create tz \
		    -cdata [timezone $curtime]] \
	     [::xmpp::xml::create display \
		    -cdata [displaytime $curtime]]]
    
    set res [::xmpp::xml::create query \
		    -xmlns jabber:iq:time \
		    -subelements $restags]
    
    return [list result $res]
}

proc timezone {time} {
    global tcl_platform

    if {[cequal $tcl_platform(platform) "windows"] && \
	    [package vcompare [info patchlevel] 8.4.12] < 0} {
	return [string trim [encoding convertfrom utf-8 \
		[encoding convertto [clock format $time -format "%Z%t"]]]]
    } else {
	return [clock format $time -format %Z]
    }
}

proc displaytime {time} {
    global tcl_platform

    if {[cequal $tcl_platform(platform) "windows"] && \
	    [package vcompare [info patchlevel] 8.4.12] < 0} {
	return [encoding convertfrom utf-8 \
		[encoding convertto [clock format $time]]]
    } else {
	return [clock format $time]
    }
}

::xmpp::iq::register get query jabber:iq:time [namespace current]::iq_time

