#!/usr/bin/tixwish

#
# initialize chart parameters
#
set strip_value1   0
set strip_value2   0
set strip_interval 1000
set strip_log1     [ list ]
set strip_log2     [ list ]
set strip_idx      0
set strip_label    ""

#
# create graphical stuff
#
label .strip_label -text "Reintegration progress"
pack .strip_label
canvas .strip_graph -height 100 -width 200 \
		    -relief sunken -border 2
pack .strip_graph

for { set x 0 } { $x < 200 } { incr x } {
  lappend strip_log1 0
  lappend strip_log2 0
}

proc strip_draw {} {
  global strip_log1 strip_value1
  global strip_log2 strip_value2
  global strip_interval strip_idx strip_label

  set strip_log1 [ lreplace $strip_log1 $strip_idx $strip_idx $strip_value1 ]
  set strip_log2 [ lreplace $strip_log2 $strip_idx $strip_idx $strip_value2 ]

  .strip_graph delete data

  # find the scale 
  set max 1
  foreach v1 $strip_log1 v2 $strip_log2 {
    if { [ expr $v1 + $v2 ] > $max } {set max [ expr $v1 + $v2 ] }
  }

  set i [ expr 202 - $strip_idx ]
  foreach v1 $strip_log1 v2 $strip_log2 {
    set val1 [ expr 66.0 * $v1 / $max ]
    set val2 [ expr 66.0 * $v2 / $max ]
    .strip_graph create line $i 103 $i [ expr 102 - $val1 ] -tags data \
			     -fill LightSlateBlue
    .strip_graph create line $i [ expr 102 - $val1 ] \
                             $i [ expr 102 - $val1 -$val2 ] \
                             -tags data -fill SkyBlue
    incr i
    if { $i >= 202 } { set i 2 }
  }
  .strip_graph create text 200 10 -text "$strip_label" -tags data -anchor e

  incr strip_idx
  if { $strip_idx >= 200 } { set strip_idx 0 }

  after $strip_interval strip_draw
}

proc strip_title {text} {
  #.strip_label configure -text $text
}

#########################################################################
#
# Venus related stuff
#
proc updatestats {} {
  global input
  #
  # Get a line (may be empty or not ready yet)
  #
  set n [ gets $input line ]
  if { $n == -1 } {
    if [ eof $input ] {
      puts "Connection to venus lost"
      exit 0
    }
    return
  }

  checkline $line
}

#
# connect to the venus port
#
set input [ socket localhost venus ]
puts "Connected to venus"
puts $input "set:fetch"
flush $input

#
# set the socket to non-blocking and attach the callback
#
fconfigure $input -blocking off
fileevent $input readable updatestats

#########################################################################
#
# Customized stuff
#
proc checkline {line} {
  global strip_value1 strip_value2 strip_label

  #
  # match our patterns
  #
  if [ regexp {^reintegrate::([^\,]+), (.+)/(.+)} $line x vol active total ] {
    set strip_value1 [ expr $total - $active ]
    set strip_value2 $active
    strip_title $vol
    if { $total == 1 } { set strip_label "1 change" } else \
    { set strip_label "$total changes" }
  }
}

#
# configure and start drawing
#
#set strip_interval 100
strip_draw
