#
# Module selectTargets.tcl
#
# $Log: selectTargets.tcl,v $
# Revision 1.2  2006/10/26 09:39:17  vfom
# Added code for netstate server query
#
#
proc addIpRange { wt mode } {
    global	addIpRange_exitFlag targetArray

    if { $mode=="edit"  & [$wt index [lrange [$wt curselection] 0 0] row ] == 0 } {
	return
    }
    set w .selectTargets.addIpRange

    if {[ winfo exists $w ]} then  {
	raise $w ;
	return
    }
    toplevel $w -class Dialog
    wm transient $w [winfo toplevel [winfo parent $w]]
    wm title $w [msgcat::mc "Enter IP address range"]
    set index 0

    frame $w.fields
    set wf $w.fields
    pack $wf -side top -fill both -expand on -padx 5 -pady 5
    
    label $wf.lstart -text [msgcat::mc "Start IP address:"]
    entry $wf.estart -width 15
    $wf.estart delete 0 end

    label $wf.lstop -text [msgcat::mc "Stop IP address:"]
    entry $wf.estop -width 15
    $wf.estop delete 0 end
    
    if { [string equal $mode "edit" ] } {
	set index  [$wt index [lrange [$wt curselection] 0 0] row ]
	$wf.estart insert 0 $targetArray($index,0)
	$wf.estop  insert 0 $targetArray($index,1)
    } 
    
    pack $wf.lstart $wf.estart $wf.lstop $wf.estop -side left -padx 5 
    
    frame $w.buttons
    set wb $w.buttons
    pack $wb -side bottom -padx 5 -pady 5
    
    button $wb.ok -text [msgcat::mc "Ok"] \
	-command "addIpRangeAction $wt $wf.estart $wf.estop $mode"

    button $wb.cancel -text [msgcat::mc "Cancel"] \
	-command "set addIpRange_exitFlag 1"
    pack  $wb.cancel $wb.ok -side right -padx 5 -pady 5

    wm withdraw $w
    update idletasks
    set x [expr {[winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \
	    - [winfo vrootx [winfo parent $w]]}]
    set y [expr {[winfo screenheight $w]/2 - [winfo reqheight $w]/2 \
	    - [winfo vrooty [winfo parent $w]]}]

    wm geom $w   +$x+$y
    wm deiconify $w
    raise $w
    set oldFocus [focus]
    set oldGrab [grab current $w]
    if {[string compare $oldGrab ""]} {
	set grabStatus [grab status $oldGrab]
    }
    grab $w
    focus $wb.ok

    tkwait variable addIpRange_exitFlag

    catch {focus $oldFocus}
    grab release $w
    destroy $w
    if {[string compare $oldGrab ""]} {
	if {![string compare $grabStatus "global"]} {
	    grab -global $oldGrab
	} else {
	    grab $oldGrab
	}
    }
    return  
}
#
proc addIpRangeAction { wt estr estp mode } {
    global targetArray addIpRange_exitFlag

    set start [ $estr get ]
    set stop  [ $estp get ]
    if { [IsValidIpAddrRange $start $stop]} {
	if { [string equal $mode "edit" ] } {
	    set index  [$wt index [lrange [$wt curselection] 0 0] row ]
	} else {
	    set nrows [ $wt cget -rows ]
	    set index $nrows
	    incr nrows
	    $wt configure -rows $nrows        
	}
	set targetArray($index,0) $start
	set targetArray($index,1) $stop
	set addIpRange_exitFlag 1
    } else {
	    tk_dialog $wt.dlg [msgcat::mc "Incorrect entry"] \
		[concat [msgcat::mc "Expected valid IP address range,\n got:"] "$start - $stop." ]\
		 error 0 [msgcat::mc "Approve" ]
    }
}
#
proc deleteIpRangeAction { wt } {
    global targetArray 

    set index  [$wt index [lrange [$wt curselection] 0 0] row ]
        
    set nrows [ $wt cget -rows ]

    if { $nrows > 1 } {
	set nrows [expr $nrows - 1 ]
        for {set i $index} {$i<$nrows} {incr i} {
	    set j [ expr $i+1]
    	    set targetArray($i,0)  $targetArray($j,0) 
            set targetArray($i,1)  $targetArray($j,1) 
        }
	$wt configure -rows $nrows
    }
}
#
proc updateTargetList { wt } {
    global targetList targetArray myLogFile activeFileChanged

    set targetList  [ list ]
    set nrows [$wt cget -rows]
    if {$nrows>1} {
	set clist [ $wt get 1,0 end ]
	set size [llength $clist] 
	for {set i 0} {$i<$size} {incr i;incr i } {
    	    lappend targetList [list [ lindex $clist $i] [ lindex $clist [expr $i+1] ]]
        }
    }
    unset [$wt cget -variable ]
    set activeFileChanged "yes"
}
#
proc loadTargets { wt } {
    global targetArray myLogFile
    set f [ tk_getOpenFile -title [msgcat::mc "Open Targets file"]]
    if { $f=="" } {
        return
    }
    if { [ catch { open $f r } fd ] } {
	tk_dialog $wt.dlg "LoadTargets"  "Can't open file: $fd." error 0 "Cancel"   
	return
    }
    set body [read $fd]
    close $fd
    set errors 0
    #
    foreach str  [ split $body "\n" ]  {
	regsub  -all {^[ 	]*} $str  {} str2
	regsub  -all  {[ 	]+$} $str2 {} str3
	regsub  -all {[ ]+} $str3 " " str2
	regsub  -all {[	]+} $str2 " " str
	set tokens [split $str]
	set tok0 [lindex $tokens 0]
	set tok1 [lindex $tokens 1]
	if {[string index $tok0 0] == "#" } {
	} elseif { $tok0 != "" && $tok1 != "" } {
	    if {[IsValidIpAddrRange $tok0 $tok1 ]} {
	        set nrows [ $wt cget -rows ]
	        set srow $nrows
	        incr nrows

	        $wt configure -rows $nrows        		
	        set targetArray($srow,0) $tok0
	        set targetArray($srow,1) $tok1
	    } else {
		puts stderr "LoadTargets: Format error: Expected valid IP addresses range, got: $tok0 $tok1. Skipping line."
		incr errors
	    }
	}
    }
    if { $errors >0 } {
	tk_dialog $wt.dlg "LoadTargets"  \
	    "There was $errors error(s).\n Look for $myLogFile." \
	     error 0 [msgcat::mc "Approve" ]
    }	
}
#    
proc saveTargets { wt } {
    global targetArray
    
    set f [ tk_getSaveFile -title [msgcat::mc "Save Targets to file"]]
    if { $f=="" } {
        return
    }
    if { [ catch { open $f w } fd ] } {
	tk_dialog $wt.dlg "SaveTargets"  "Can't open file: $fd." error 0 [msgcat::mc "Approve" ]
	return
    }

    set nrows [ $wt cget  -rows ]
    if { $nrows > 1 }  {
	for {set i 1} { $i<$nrows} {incr i} {
	    puts $fd "$targetArray($i,0)		$targetArray($i,1)"
	}
    }	
    close $fd
}
#
#		
#
#
proc selectTargets { } {
    global targetList targetArray
        
    set w .selectTargets

    if {[ winfo exists $w ]} then {
	raise $w 
	return
    }
    toplevel $w -class Dialog
    wm transient $w [winfo toplevel [winfo parent $w]]
    wm title $w [msgcat::mc "Select Targets"]

    frame $w.tableFrame
    set wf $w.tableFrame
    pack $wf -side top -fill both -expand on -padx 5 -pady 5
    set wt $wf.table

    set targetArray(0,0) [msgcat::mc "Start IP"]
    set targetArray(0,1) [msgcat::mc "Stop IP" ]

    table $wt -rows 1 -cols 2 \
	-variable targetArray \
	-titlerows 1 -titlecols 0 \
	-yscrollcommand " $wf.sy set "  \
	-roworigin 0 -colorigin 0 \
	-maxwidth 200 -maxheight 300 \
	-selectmode browse \
	-rowstretch none -colstretch all \
	-flashmode 0 \
	-state disabled \
	-background #f700f700f700 \
	-borderwidth 2 \
	-drawmode single \
	-selecttype row	\
	-resizeborders none	\
	-anchor w

    scrollbar $wf.sy -command [list $wt yview]
    pack $wf.sy -side right  -fill y
    pack $wt -side top -fill both -expand on
    $wt tag config title -bg #0000bf00ff00 -relief groove
    $wt tag config sel -fg #f700f700f700 -bg #48003d008b00 

    frame $w.buttonFrame 
    set wb $w.buttonFrame

    button $wb.ins  -text [msgcat::mc "New"] \
	-command "addIpRange  $wt new"
    button $wb.edit -text [msgcat::mc "Edit"]\
	-command "addIpRange $wt edit"
    button $wb.del  -text [msgcat::mc "Delete"] \
	-command "deleteIpRangeAction $wt"
    pack $wb.ins $wb.edit $wb.del -side left  -padx 5 -pady 5

    frame $w.buttonFrame1
    set wb $w.buttonFrame1

    button $wb.load  -text [msgcat::mc "Load from file"] \
	-command "loadTargets $wt"
    button $wb.save  -text [msgcat::mc "Save to file"] \
	-command "saveTargets $wt"
    pack $wb.load $wb.save -side left  -padx 5 -pady 5

    frame $w.buttonFrame2 
    set wb $w.buttonFrame2
    button $wb.ok -text [msgcat::mc "Ok"] \
	-command "updateTargetList $wt; set selectTargets_exitFlag 1"

    button $wb.cancel -text [msgcat::mc "Cancel"] \
	-command "set selectTargets_exitFlag 1"
    pack $wb.ok $wb.cancel -side left  -padx 5 -pady 5
						    
    pack $w.buttonFrame $w.buttonFrame1 $w.buttonFrame2 -side top -pady 5

    if { [lindex $targetList 0] != "" }  {
	set n_pairs [ llength $targetList ]
        $wt configure -rows [expr $n_pairs + 1 ]
	for {set i 1} { $i<=$n_pairs} {incr i} {
	    set pair [lindex $targetList [expr $i-1]]
    	    set targetArray($i,0) [ lindex $pair 0 ]
    	    set targetArray($i,1) [ lindex $pair 1 ]
	}
    }	

    wm withdraw $w
    update idletasks
    set x [expr {[winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \
	    - [winfo vrootx [winfo parent $w]]}]
    set y [expr {[winfo screenheight $w]/2 - [winfo reqwidth $w] \
	    - [winfo vrooty [winfo parent $w]]}]
    set wd [winfo reqwidth $w ]
    set h [expr $wd *2 ]
    

    wm geom $w [format "%sx%s+%s+%s" $wd $h  $x $y]
    wm deiconify $w
    raise $w
    set oldFocus [focus]
    set oldGrab [grab current $w]
    if {[string compare $oldGrab ""]} {
	set grabStatus [grab status $oldGrab]
    }
    grab $w
    focus $wb.ok

    tkwait variable selectTargets_exitFlag

    catch {focus $oldFocus}
    grab release $w
    destroy $w
    if {[string compare $oldGrab ""]} {
	if {![string compare $grabStatus "global"]} {
	    grab -global $oldGrab
	} else {
	    grab $oldGrab
	}
    }
    return 
}
#    
