#!/usr/bin/ruby

# dm_status3 10-8-2009
# ruby gtk GUI in the style of the interlock GUI

require 'gtk2'
require 'socket'
require 'timeout'

$:.unshift "/mmt/scripts"
require 'MMTsocket.rb'

# ----------------------------------------------------------

# A clabel is a box with text, capable of having a
# background color set
class	Clabel < Gtk::EventBox

	GREEN = Gdk::Color.new(0, 65535, 0)
	YELLOW = Gdk::Color.new(65535, 65535, 0)
	RED = Gdk::Color.new(65535, 0, 0)
	SKYBLUE =  Gdk::Color.new(34695, 52942, 60395)
	SKYBLUE1 =  Gdk::Color.new(34695, 52942, 65535)
	WHITE =  Gdk::Color.new(65535, 65535, 65535)

	def set_text ( text )
	    return if @text == text
	    @lab.set_text( "  " + text + "  " )
	    @text = text
	end

	def set_color ( color )
	    return if @color == color
	    @color = color
	    modify_bg( Gtk::STATE_NORMAL, color )
	end

	def initialize ( text, tag )
	    super()
	    set_color( WHITE )
	    @lab = Gtk::Label.new( text )
	    @text = text
	    add( @lab )
	    @tag = tag
	end

	def update ( vals )
	    newv = vals[@tag]
	    newv = "NA" unless newv

	    if @tag == "tss_status"
		if newv == "SAFE MODE"
		    set_color GREEN
		else
		    set_color YELLOW
		end
	    end

	    @lab.set_text newv
	end
end

class	Slabel < Gtk::EventBox

	WHITE =  Gdk::Color.new(65535, 65535, 65535)
	GREY =  Gdk::Color.new(50000, 50000, 50000)

	def set_color ( color )
	    return if @color == color
	    @color = color
	    modify_bg( Gtk::STATE_NORMAL, color )
	end

	def left
	    @lab.xalign = 1
	end

	def initialize ( text )
	    super()
	    set_color( GREY )
	    @lab = Gtk::Label.new( text )
	    add( @lab )
	end
end

# actually two side by side columns, but to get them
# to have a uniform width, must make two columns, not
# a single column of Hboxes.
class Hcolumn
	def initialize ( argbox )
	    if argbox.class == "GTK::HBox"
		box = argbox
            else
		box = Gtk::HBox.new false, 0
	        argbox.add box
	    end
	    @lcol = Gtk::VBox.new true, 0
	    @rcol = Gtk::VBox.new true, 0
	    box.pack_start @lcol, true, true, 1
	    box.pack_start @rcol, true, true, 1
	end
	def add ( label, tag )
	    lab = Slabel.new( label )
	    lab.left
	    @value = Clabel.new( "", tag )
	    @lcol.pack_start lab, true, true, 0
	    @rcol.pack_start @value, true, true, 0
	    DMstatus.add_update @value
	end
end

class Vcolumn
	def initialize ( box )
	    @col = Gtk::VBox.new true, 0
	    if box.class == "GTK::HBox"
	        box.pack_start @col, true, true, 1
	    else
	        box.add @col
	    end
	end
	def add ( label, tag )
	    @tag = tag
	    lab = Slabel.new( label )
	    @value = Clabel.new( "", tag )
	    @col.pack_start lab, true, true, 0
	    @col.pack_start @value, true, true, 0
	    DMstatus.add_update @value
	end
end

class	IMenuBar < Gtk::MenuBar
	GREEN = Gdk::Color.new(0, 65535, 0)
	RED = Gdk::Color.new(65535, 0, 0)
	YELLOW = Gdk::Color.new(65535, 65535, 0)

	def initialize ()
	    super()
	end
	def set_color ( color )
	    return if @color == color
	    @color = color
	    modify_bg( Gtk::STATE_NORMAL, color )
	end
	def on ()
	    set_color( GREEN )
	end
	def off ()
	    set_color( RED )
	end
	def warn ()
	    set_color( YELLOW )
	end
end

# --------------------------------------------------
# --------------------------------------------------

class DMstatus < Gtk::Window

    @@things = Array.new

    def DMstatus.add_update ( item )
	@@things << item
    end

    def DMstatus.update ( vals )
	@@things.each { |x| x.update( vals ) }
    end

    @@debug = nil

    def DMstatus.debug
    	@@debug = 1
    end

    def initialize

	@debug = @@debug

	Gtk.init

	super()
    end

    def build_gui
	set_title( "Adaptive Secondary Status" )
	border_width = 5

	signal_connect( 'delete_event' ) { false }
	signal_connect( 'destroy' ) { Gtk.main_quit }

	# ----- -----

	# We get access to the background color
	# for the entire menu bar this way.
	# Not exactly what we want, but better
	# than nothing.  I have had no luck so
	# far putting color on a menuitem.
	mbar = IMenuBar.new
	$status = mbar	# handle for network LED

	# -----

	item = Gtk::MenuItem.new('Quit')
	item.signal_connect('activate') {
	    Gtk.main_quit
	}

	filemenu = Gtk::Menu.new
	filemenu.add item

	mbar_file = Gtk::MenuItem.new('File')
	mbar_file.set_submenu filemenu
	mbar.append mbar_file

	#---------------------------------------------------------------------

	mainbox  = Gtk::VBox.new( false, 0 )
	add mainbox

#	packstart	window, expand, fill, padding

	mainbox.pack_start mbar, true, true, 0

	frame = Gtk::Frame.new
	mainbox.pack_start frame, true, true, 0

	top_box  = Gtk::HBox.new( false, 0 )
	frame.add top_box

	frame = Gtk::Frame.new
	top_box.pack_start frame, true, true, 0

	col = Vcolumn.new( frame )

	#col.add "ADAPTIVE SECONDARY STATUS", "tss_status"
	#col.add "Current Applied (Amps)", "total_current"
	col.add "TSS Status", "tss_status"
	col.add "Total Current (Amps)", "total_current"

	frame = Gtk::Frame.new
	top_box.pack_start frame, true, true, 0

	top2_box  = Gtk::HBox.new( false, 0 )
	frame.add top2_box

	col = Hcolumn.new( top2_box )

	col.add "VCC_P Current (Amps) ", "power_vccp"
	col.add "VSS_P Current (Amps) ", "power_vssp"
	col.add "VCC_P Voltage (V) ", "voltage_vccp"
	col.add "VSS_P Voltage (V) ", "voltage_vssp"
	col.add "VCC_A Voltage (V) ", "voltage_vcca"
	col.add "VSS_A Voltage (V) ", "voltage_vssa"
	col.add "VCC_L Voltage (V) ", "voltage_vccl"

	col = Hcolumn.new( top2_box )

	col.add "HW coil (red mushroom) ", "enable_coil_hw"
	col.add "SW coil (tss logic) ", "enable_coil_sw"
	col.add "Coil Status (HW and SW) ", "coil_status"
	col.add "TSS Command ", "command"
	col.add "Power Status ", "power_status"
	col.add "Fiber to DM ", "fiber_status"
	col.add "Wrong command sent ", "wrong"

	frame = Gtk::Frame.new
	mainbox.pack_start frame, true, true, 0
	mid_box  = Gtk::HBox.new( false, 0 )
	frame.add mid_box

	col = Hcolumn.new( mid_box )
	col.add "Crate 1 Temperature (deg C) ", "temp_crate1"
	col.add "Crate 2 Temperature (deg C) ", "temp_crate2"
	col.add "Crate 3 Temperature (deg C) ", "temp_crate3"
	col.add "Max crate temperature (deg C) ", "max_crate_temp"
	col.add "Ambient Temperature (deg C) ", "temp_ambient"
	col.add "Water inlet Pressure (PSI) ", "pressure_inlet"

	col = Hcolumn.new( mid_box )

	col.add "Water inlet Temperature (deg C) ", "temp_water_inlet"
	col.add "Water outlet Temperature (deg C) ", "temp_water_outlet"
	col.add "Coldplate 1 Temperature (deg C) ", "temp_coldplate1"
	col.add "Coldplate 2 Temperature (deg C) ", "temp_coldplate2"
	col.add "Ambient Humidity (RU %) ", "humidity_ambient"
	col.add "Water outlet Pressure (PSI) ", "pressure_outlet"

	frame = Gtk::Frame.new
	mainbox.pack_start frame, true, true, 0
	bot_box  = Gtk::HBox.new( false, 0 )
	frame.add bot_box

	col = Hcolumn.new( bot_box )
	col.add "Set Current on TSS ", "current_on_tss"
	col.add "Delta Current for Push ", "max_hold2"
	col.add "Overcurrent on Vccp rail ", "overcurrent_vccp"
	col.add "Overcurrent on vccp-vssp (push) ", "overcurrent_push"

	col = Hcolumn.new( bot_box )
	col.add "Max Current Vccp and Vssp rail ", "max_hold1"
	col.add "Delta Current for Pull ", "max_hold3"
	col.add "Overcurrent on Vssp rail ", "overcurrent_vssp"
	col.add "Overcurrent on vssp-vccp (pull) ", "overcurrent_pull"

	show_all
    end
end

# ---------------------------------------------------------------------
# ---------------------------------------------------------------------

class Netdata
    def initialize ( host, port )
		@host = host
		@port = port
		@net_thread = nil
		@vals = nil
		@timeout = 1

		# statistics
		@count = 0
		@timeouts = 0
		@overruns = 0
		@stat_counter = 0
		@maxwait = 0
    end

    def net_ticker ()

	conn = MMTsocket.new( @host, @port )
	if conn.status
#	    print "Oops: #{conn.status}\n"
	    conn = nil
	    @vals = nil
	    return
	end
	conn.ident( "dm_status" )

	@vals = conn.values
	#@vals['net_count'] = @count.to_s
	#@vals['net_timeouts'] = @timeouts.to_s
	#@vals['net_overruns'] = @overruns.to_s

	conn.done

	DMstatus.update( @vals )

    end

    def ticker
#	stats()
	if @net_thread and @net_thread.alive?
	    $status.off
	    @overruns += 1
	    @timeout += 1
	    return if @timeout < 10
	    @net_thread.kill
	    @timeouts += 1
	end

	$status.on if @timeout == 0

	@maxwait = @timeout if @timeout > @maxwait

	@count += 1
	@net_thread = Thread.new { net_ticker() }
	@timeout = 0 if @vals

    end

    # called at 1 Hz, prints every tenth call.
    def stats
	@stat_counter += 1
	return if @stat_counter < 10
	@stat_counter = 0
    	print @count, " (#{@overruns}:#{@maxwait}/#{@timeouts})\n"
    end
end

# ---------------------------------------------------------------------

Delay = 1000

if $0 == __FILE__

    port = 7003
    host = "ao-server"
#    host = "hacksaw"

    verbose = nil

    loop {
	a = ARGV.shift
	break unless a
	case a
	    when /-v/
		verbose = 1
	    when /-d/
		DMstatus.debug
	    else
		print "ignoring option: #{a}\n"
	    end
    }

    if verbose
	    print "Talking to #{host} on #{port}\n"
    end

    DMstatus.new.build_gui

    $net = Netdata.new( host, port )

    $blink = 0

    Gtk.timeout_add( Delay ) {
	$blink = 1 - $blink
	$net.ticker()
	true
    }

    Gtk.main

end

# THE END
