namespace eval gateway {
    variable msgid 0

    hook::add roster_service_popup_menu_hook \
	[namespace current]::add_menu_item 30
}

proc gateway::add_menu_item {m connid jid} {

    $m add command -label [::msgcat::mc "Add user to roster..."] \
	-command [list [namespace current]::subscribe_dialog $connid $jid]
}

proc gateway::subscribe_dialog {connid service} {
    variable msgid

    set mw .gwmsg$msgid
    toplevel $mw
    wm group $mw .

    set title [format [::msgcat::mc "Send subscription at %s"] $service]
    
    wm title $mw $title
    wm iconname $mw $title

    set bbox [ButtonBox $mw.buttons -spacing 0 -padx 10 -default 0]
    $bbox add -text [::msgcat::mc "Subscribe"] \
        -command [list [namespace current]::send_subscribe $mw $connid $service]
    $bbox add -text [::msgcat::mc "Cancel"] -command [list destroy $mw]

    bind $mw <Return> "ButtonBox::invoke $bbox default"
    bind $mw <Escape> "ButtonBox::invoke $bbox 1"

    pack $bbox -side bottom -anchor e -padx 2m -pady 2m

    set sep [Separator::create $mw.sep -orient horizontal]
    pack $sep -pady 1m -fill x -side bottom

    frame $mw.frame
    pack $mw.frame -side top -fill both -expand yes -padx 2m -pady 2m

    label $mw.prompt
    pack $mw.prompt -side top -anchor w -in $mw.frame

    variable $mw.prompt fulljid
    bind $mw <Destroy> [list catch [list unset [namespace current]::$mw.prompt]]

    jlib::send_iq get \
        [jlib::wrapper:createtag query \
             -vars {xmlns jabber:iq:gateway}] \
	-to $service \
        -command [list [namespace current]::configure_prompt $mw.prompt] \
	-connection $connid

    frame $mw.subj
    label $mw.subj.lab -text [::msgcat::mc "Send subscription to: "]
    entry $mw.subj.entry
    pack $mw.subj.lab -side left
    pack $mw.subj.entry -side left -fill x -expand yes
    pack $mw.subj -side top -anchor w -fill x -expand yes -in $mw.frame

    frame $mw.space
    pack $mw.space -side top -fill x -in $mw.frame -pady 0.5m

    ScrolledWindow $mw.sw
    pack $mw.sw -side top -fill both -expand yes -in $mw.frame

    textUndoable $mw.body -width 60 -height 8 -wrap word
    $mw.body insert 0.0 [::msgcat::mc "I would like to add you to my roster."]
    pack $mw.body -side top -fill both -expand yes -in $mw.sw
    $mw.sw setwidget $mw.body

    focus $mw.subj.entry

    incr msgid
}

proc gateway::configure_prompt {w res child} {
    if {![winfo exists $w]} return

    $w configure \
	-text [::msgcat::mc "Enter screenname of contact you want to add"]
    
    if {$res != "OK"} {
	return
    }

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

    foreach ch $children {
	jlib::wrapper:splitxml $ch tag1 vars1 isempty1 chdata1 children1

	if {($tag1 == "desc") && ($chdata1 != "")} {
	    $w configure -text $chdata1
	    variable $w screenname
	    break
	}
    }
}

proc gateway::send_subscribe {mw connid service} {
    variable $mw.prompt
    
    switch -- [set $mw.prompt] {
	fulljid {
	    $mw.subj.entry insert end "@$service"
	    message::send_subscribe $mw -connection $connid
	}
	screenname {
	    set screenname [$mw.subj.entry get]
	    jlib::send_iq set \
		[jlib::wrapper:createtag query \
		     -vars {xmlns jabber:iq:gateway} \
		     -subtags [list [jlib::wrapper:createtag prompt \
					 -chdata $screenname]]] \
		-to $service \
		-command [list [namespace current]::gw_send_subscribe $mw \
			       "$screenname@$service" \
			       $connid] \
		-connection $connid
	}
    }
}

proc gateway::gw_send_subscribe {mw fallback connid res child} {

    set jid $fallback

    if {$res == "OK"} {
	jlib::wrapper:splitxml $child tag vars isempty chdata children

	foreach ch $children {
	    jlib::wrapper:splitxml $ch tag1 vars1 isempty1 chdata1 children1

	    if {($tag1 == "jid" || ($tag1 == "prompt")) && \
		    ($chdata1 != "")} {
		set jid $chdata1
		break
	    }
	}
    }
    
    $mw.subj.entry delete 0 end
    $mw.subj.entry insert 0 $jid
    message::send_subscribe $mw -connection $connid
}


proc gateway::convert_jid {jid args} {

    foreach {opt val} $args {
	switch -- $opt {
	    -connection {set connid $val}
	}
    }
    if {![info exists connid]} {
	return -code error "Option -connection mandatory"
    }

    jlib::send_iq get \
        [jlib::wrapper:createtag query \
             -vars {xmlns jabber:iq:gateway}] \
	-to $jid \
        -command [list [namespace current]::convert_jid_dialog \
		       $jid $connid] \
	-connection $connid
}

proc gateway::convert_jid_dialog {jid connid res child} {
    variable msgid

    if {$res != "OK"} return

    set w .gwmsg$msgid

    Dialog $w -title [::msgcat::mc "Screenname conversion"] \
        -separator 1 -anchor e -modal none \
	-default 0 -cancel 1

    set f [$w getframe]

    $w add -text [::msgcat::mc "Convert"] \
        -command [list [namespace current]::convert_screenname $w $connid $jid]
    $w add -text [::msgcat::mc "Cancel"] -command [list destroy $w]

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

    set row 0
    foreach ch $children {
	jlib::wrapper:splitxml $ch tag1 vars1 isempty1 chdata1 children1

	switch -- $tag1 {
	    desc {
		if {![winfo exists $f.desc]} {
		    message $f.desc -text $chdata1 -width 15c
		    grid $f.desc -row $row -column 0 \
			-columnspan 2 -sticky w -pady 2m
		}
	    }
	    prompt {
		if {![winfo exists $f.prompt]} {
		    label $f.lprompt -text [::msgcat::mc "Screenname:"]
		    entry $f.prompt
		    grid $f.lprompt -row $row -column 0
		    grid $f.prompt -row $row -column 1 -sticky ew -padx 1m
		}
	    }
	}
	incr row
    }

    incr msgid

    $w draw $f.prompt
}

proc gateway::convert_screenname {w connid jid} {
    set f [$w getframe]
    set screenname [$f.prompt get]
    
    destroy $w
    
    jlib::send_iq set \
	[jlib::wrapper:createtag query \
	     -vars {xmlns jabber:iq:gateway} \
	     -subtags [list [jlib::wrapper:createtag prompt \
				 -chdata $screenname]]] \
	-to $jid \
	-command [list [namespace current]::display_conversion $w $screenname] \
	-connection $connid
}

proc gateway::display_conversion {w screenname res child} {

    if {$res != "OK"} {
	NonmodalMessageDlg $w -aspect 50000 -icon error \
	    -message [format [::msgcat::mc "Error while converting screenname: %s."] \
			  [error_to_string $child]]
    } else {
	set jid ""

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

	foreach ch $children {
	    jlib::wrapper:splitxml $ch tag1 vars1 isempty1 chdata1 children1

	    if {($tag1 == "jid" || ($tag1 == "prompt")) && \
		    ($chdata1 != "")} {
		set jid $chdata1
		break
	    }
	}
	
	NonmodalMessageDlg $w -aspect 50000 \
	    -title [::msgcat::mc "Screenname conversion"] \
	    -message [format [::msgcat::mc "Screenname: %s\n\nConverted JID: %s"] \
			  $screenname $jid]
    }
}

hook::add postload_hook \
    [list disco::browser::register_feature_handler jabber:iq:gateway \
	  [namespace current]::gateway::convert_jid \
	  -desc [list * [::msgcat::mc "Convert screenname"]]]

