=begin
 ******************************************************************************
 * Copyright 1990-2009 MBARI
 * MBARI Proprietary Information. All rights reserved.
 ******************************************************************************
 * Summary  : Implemetation of the ChamberImages behavior
 * Filename : fluoro_image.rb
 * Author   : Henthorn
 * Project  : Benthic Rover
 * Version  : 1
 * Created  : June 09
 * Modified : 
 ******************************************************************************
=end

# Refer to Rover-code home directory as base
#
require "#{ENV['ROVER_HOME']}/utils/rover_environment"
#

require "utils/misc"
require "control/behavior"
require 'device/rover'

##########
# FluoroImage class.
# Capture image using the fluorometry camera.
#
class FluoroImage < Behavior
  include RoverTime

  #####
  # Accept a behavior element and extract parameters
  #
  def initialize(p_behavior_element)
    super

    @prefix = "fluoro"
    load_attrs(p_behavior_element)
  end
  #####


  #####
  # A crude documentation feature. Each subclass should provide
  # one that begins by calling this method.
  #
  def FluoroImage.usage
    u  = sprintf(Behavior.usage_format, \
                 "prefix","Prepends to image filenames","String","blank")
    u += "\n<FluoroImage name=\"Example\" prefix=\"fluoro\" "
    u += "comment=\"Prepends 'fluoro' to image filenames\" />\n"
  end


  #####
  # Iterate over attributes in the element, extract parameters.
  #
  def load_attrs(p_behavior_element)
    super

    attrs = p_behavior_element.attributes
    attrs.keys.each do |k|
      case k

        # Get the prefix for these images
        when "prefix"
        @prefix = attrs[k]

#       else
#       puts("Unrecognized attr: #{k}")

      end
    end

    # Option: Throw an exception if there any required attributes
    # missing
    #
  end
  #####


  #####
  # Initialize behavior and make ready for execution.
  # Should be called just before executing the behavior.
  #
  def init(p_seq_number=1)   # Where in the plan behavior sequence I am
    syslog("_ #{@name} init")
    self.data_home = p_seq_number

    # Perform initialization procedures
    @state = READY
  end
  #####


  #####
  # Create directory to hold images
  #
  def data_home=(p_seq_num)
    mn_zero = p_seq_num > 9 ? "" : "0"
    home_prefix = mn_zero + p_seq_num.to_s
    DataLog.behavior_data_home = @data_home = home_prefix + "-fluoro_camera/"
  end
  #####

  #####
  # Execute the behavior
  #
  def execute
    # Execute if ready.
    unless (@state == READY)
      syslog("! #{name} not in ready state")
      return
    end

    syslog("_ #{@name} executing")
    @state = EXECUTING

    ##
    # Run the behavior even if the health
    # of the fluoro cam is less than OK.
    #
    health = Supervisor.instance.dbif.load_component_state(RoverStore::FluoroCam)
    if (health[RoverStore::Health])
      syslog("! FluoroCam health is less than optimal. Continue...")
    end

    # Perform the behavior
    begin

      ##
      # Power-up the fluorometry camera, capture them image
      # using Snap and move the image file to the data directory
      # using the prefix, if any.
      # Make sure chamber cameras are off.
      #
      Rover.instance.relay.camerasOff
      Rover.instance.ethernet(true)
      Rover.instance.relay.fluoroOn
      sleep(10)

      pro = Rover.instance.fluoro_cam
      #image_name = DataLog.behavior_data_home + "fluoro_" + @prefix
      image_name = DataLog.behavior_data_home + @prefix

      # Make 3 attempts to capture an image
      #
      for i in 1..3
        break if (pro.capture_image(image_name))
        syslog("! Unable to capture #{image_name} image")
      end

      syslog("_ #{@name} complete")
    ensure
      self.clean_up()
    end
  end
  #####


  #####
  def clean_up
    Rover.instance.ethernet(false)
    Rover.instance.relay.fluoroOff
  end
  #####


  #####
  # Abort the behavior
  #
  def abort
    syslog("_ #{@name} abort")
    if (@state == EXECUTING)
      @state = ABORTING 

      # Kill the run thread, clean up
      @my_thread.kill if @my_thread
      clean_up
    else
      syslog("_ #{@name} not executing, aborting...")
    end
  end
  #####


  #####
  # Test method. Use to run standard test of MyClass from
  # a ruby script.
  # 
  def FluoroImage.test
    require 'rexml/document'
    require 'device/rover'

    Rover.instance
    # Test code here
    fluoro_xml=REXML::Document.new(File.new(Misc.find_plan("test_fluoro.xml")))
    ci = FluoroImage.new(fluoro_xml.root)
    ci.init
    ci.execute
    puts("Done")
  end
  #####

end

#####
# Standalone unit test (recommended)
# Include at the end of the file as a hook to run a unit test of
# the code from the command line including the command line options
# (e.g., "$ ruby my_class.rb --sim").
#
if __FILE__ == $0
  if "usage" == ARGV[0]
    puts(Behavior.usage)
    puts(FluoroImage.usage)
    exit(0)
  end

  FluoroImage.test
end
