# $Id: killerfeature.tcl 155 2008-10-21 12:51:53Z kostix $
# "Killer Feature" -- account removal support plugin for Tkabber.
# Written by Konstantin Khomoutov <flatworm@users.sourceforge.net>

namespace eval killerfeature {
	variable state

	hook::add finload_hook [namespace current]::init
	hook::add connected_hook [namespace current]::update_state
	hook::add disconnected_hook [namespace current]::update_state
}

proc killerfeature::init args {
	set m [[. cget -menu] entrycget Tkabber -menu]
	set ix [$m index [::msgcat::mc "Log out with reason..."]]
	$m insert [incr ix] command \
		-label [::msgcat::mc "Delete account..."] \
		-command [namespace current]::zap_dialog
}

proc killerfeature::update_state args {
	set enabled [expr {[llength [connections]] != 0}]
}

proc killerfeature::myentry m {
	set path [list Tkabber \
		[::msgcat::mc "Log out with reason"] \
		[::msgcat::mc "Delete account..."]]
	foreach entry [lrange $path 0 end-1] {
		set m [$m entrycget $entry -menu]
	}

	$m index [lindex $path end]
}

proc killerfeature::zap_dialog {} {
	set connids [connections]
	if {[llength $connids] == 0} return

	set w [Dialog .zapaccount \
		-default 0 -cancel 1 -separator on \
		-title [::msgcat::mc "Delete account(s)"]]
	$w add -text OK
	$w add -text [::msgcat::mc "Cancel"]

	set f [$w getframe]

	set accs [list]
	foreach xlib $connids {
		lappend accs [list [connection_bare_jid $xlib] $xlib]
	}
	set accs [lsort -unique -index 0 $accs]

	variable state
	array unset state *
	set n 0
	foreach acc $accs {
		lassign $acc jid xlib
		checkbutton $f.$n -text $jid \
			-variable [namespace current]::state($xlib)
		pack $f.$n -side top -anchor w
		incr n
	}

	set choice [$w draw]
	destroy $w
	if {$choice != 0} return

	foreach acc $accs {
		lassign $acc jid xlib
		if {$state($xlib)} {
			zap $xlib
		}
	}

	array unset state *
}

proc killerfeature::zap xlib {
	xmpp::sendIQ $xlib set \
		-query [::xmpp::xml::create query \
			-xmlns jabber:iq:register \
			-subelements [list [::xmpp::xml::create remove]]] \
		-command [list [namespace current]::parse_iq_resp $xlib]
	logout $xlib
}

proc killerfeature::parse_iq_resp {xlib res child} {
}

