# $Id: challenge.tcl 1419 2008-05-13 17:56:14Z sergei $
#
# Robot challenge support (XEP-0158)
#

namespace eval challenge {}

###############################################################################

proc challenge::process_x {rowvar bodyvar f x connid from id type replyP} {
    upvar 2 $rowvar row
    upvar 2 $bodyvar body

    set challenge 0
    foreach xa $x {
	jlib::wrapper:splitxml $xa tag vars isempty chdata children

	set xmlns [jlib::wrapper:getattr $vars xmlns]
	if {$xmlns != $::NS(challenge)} continue

	set challenge 1
	foreach child $children {
	    jlib::wrapper:splitxml $child tag1 vars1 isempty1 chdata1 children1
	    set xmlns1 [jlib::wrapper:getattr $vars1 xmlns]
	    if {$xmlns1 == $::NS(data) && ![lempty $children1]} {
		if {[catch {process_x_data $f $connid $from $child}]} {
		    # Cannot process challenge form, so falling back to a
		    # legacy challenge method if any.
		    # TODO: Show error message to user.
		    set challenge 0
		}
	    }
	}
    }
    if {!$challenge} {
	return
    } else {
	set body ""
	return stop
    }
}

hook::add message_process_x_hook [namespace current]::challenge::process_x 10

proc challenge::process_x_data {f connid from x} {
    data::draw_window [list $x] [list [namespace current]::send_x_data $connid $from]
}

proc challenge::send_x_data {connid to w restags} {
    jlib::send_iq set \
	[jlib::wrapper:createtag challenge \
	     -vars [list xmlns $::NS(challenge)] \
	     -subtags $restags] \
	-to $to \
	-connection $connid
    destroy $w
}

