#
# Module LoadHostsFile.tcl  
#
# $Log: LoadHostsFile.tcl,v $
# Revision 1.2  2006/10/26 09:39:17  vfom
# Added code for netstate server query
#
#
# Procedure reads text file in "/etc/hosts" format
# and expand all ip addresses to nodes.
# So  IP address -> node_ip(CCC)
#     name       -> node_name(CCC) 
#    all other   -> node descr(CCC)
#
# Nodes autoplaced with default icon.
#
proc   LoadHostsFile { f } {
    global nodeIcon node_ip node_descr startX startY nodeFont nodeFontColor node_key
    global h_autoplacement w_autoplacement 
    #
    if { $f =="" } { return }
    if { [ catch { open $f r } fd ] } {
	tk_dialog .loadHostsFile "Load Hosts File" \
	    "Can't load file \"$f\": $fd"	   \
	    error 0 [msgcat::mc "Approve"]
	return
    }
    set body [read $fd]
    close $fd
    #
    set scroll_reg [ grid bbox .grid 0 0 0 0 ]
    set curr_width [expr [lindex $scroll_reg 2] - [lindex $scroll_reg 0] ]
    set i_w [image width $::arIcons($nodeIcon)]
    set i_h [image height $::arIcons($nodeIcon)]
    set startX 0
    set startY 0
    # AutoPlace new nodes below all known objects
    foreach obj [.canvas find all] {
	set obj_tags [.canvas itemcget $obj -tags]
	if { [string match {bgimage} $obj_tags  ] } { continue }
	set bounds [.canvas bbox $obj ]
	set rdy [lindex $bounds 3]
	if { $rdy > $startY } { set startY $rdy } 
    }
    set startY [expr $startY + $h_autoplacement ]
    foreach str  [ split $body "\n" ]  {
	regsub  -all {^[ 	]*} $str  {} str2
	regsub  -all  {[ 	]+$} $str2 {} str3
	regsub  -all {[ ]+} $str3 " " str
	set tokens [split $str]
	set tok0 [lindex $tokens 0]
	set tok1 [lindex $tokens 1]
	if {[string index $tok0 0] == "#" } {
	} elseif {$tok0 != "" } {
	    #   if {![isValidIpAddress $tok0]} {error "Invalid file format. Expected IP address, got: $tok0"; return }
	    if {$tok1 !=""} { 
		set name   $tok1 
		set descr  [join [join [lrange $tokens 2 end ]]]
	    } else {
		set name   $tok0 
		set descr  ""
	    }
	    
	    if {![info exists node_key($name)]} {
		set startX  [ expr  $startX + $w_autoplacement  ]
		if { $startX >= $curr_width } {
		    set startX  $w_autoplacement
		    set startY [expr $startY + $h_autoplacement  ]
		}
		#                                   name     X       Y       icon     font        fontColor
		set hostKey  [ CreateNodeNoUpdate  $name  $startX $startY $nodeIcon  $nodeFont  $nodeFontColor ]
		set node_ip($hostKey)    "$tok0"
		set node_descr($hostKey) "$descr"
	    } else { 
		puts "LoadHostsFile: Duplicated hostname: $name !(Skipped.)"
	    }
	}
    }
    updateScrollRegion {}
}
#
