#
# Private XML Storage (XEP-0049) support
#

namespace eval private {}

proc private::store {query args} {
    set command ""
    foreach {key val} $args {
	switch -- $key {
	    -command { set command $val }
	    -connection { set connid $val }
	}
    }

    if {![info exists connid]} {
	return -code error "private::store: -connection is mandatory"
    }

    jlib::send_iq set \
	[jlib::wrapper:createtag query \
	     -vars [list xmlns $::NS(private)] \
	     -subtags $query] \
	-command [list [namespace current]::store_result $command] \
	-connection $connid
}

proc private::store_result {command res child} {
    if {$command != ""} {
	uplevel #0 $command [list $res $child]
    }
}

proc private::retrieve {query args} {
    set command ""
    foreach {key val} $args {
	switch -- $key {
	    -command { set command $val }
	    -connection { set connid $val }
	}
    }

    if {![info exists connid]} {
	return -code error "private::retrieve: -connection is mandatory"
    }

    jlib::send_iq get \
	[jlib::wrapper:createtag query \
	     -vars [list xmlns $::NS(private)] \
	     -subtags $query] \
	-command [list [namespace current]::retrieve_result $command] \
	-connection $connid
}

proc private::retrieve_result {command res child} {
    if {$command == ""} return

    if {$res != "OK"} {
	uplevel #0 $command [list $res $child]
	return
    }

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

    uplevel #0 $command [list OK $children]
}

