=begin
 ******************************************************************************
 * Copyright 1990-2009 MBARI
 * MBARI Proprietary Information. All rights reserved.
 ******************************************************************************
 * Summary  : Sample behavior class
 * Filename : sample_behavior.rb
 * Author   : Henthorn
 * Project  : Benthic Rover
 * Version  : 1
 * Created  : Oct 2008
 * Modified :
 ******************************************************************************
=end

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

require "utils/misc"
require "control/behavior"

##########
# Demonstration of intended use of Behavior class and subclasses
#
class SampleBehavior < Behavior
  include SyslogWriter

  ##
  # Construct a SampleBehavior object given from a document element
  #
  def initialize(p_behavior_element)
    super

    @exception = false # Throw an exception during execute
    @param = nil       # Must be specified in the behavior element
    @name = self.class.name
    load_attrs(p_behavior_element)

  end

  ##
  # Iterate over attributes in the element, extract parameters.
  #
  def load_attrs(p_behavior_element)
    attrs = p_behavior_element.attributes
    attrs.keys.each do |k|
      case k
	when "name"
	@name = attrs[k].to_s
	
	when "sample_param"
	@param = attrs[k].to_s.to_i

	when "exception"
	@exception = true if (attrs[k].to_s.upcase! == "TRUE")

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

      end
    end

    # Option: Throw an exception if there any required attributes
    # are missing
    #
    raise("'sample_param' attribute must be specified!") unless @param
  end


  ##
  # Override init.
  # Do some initialization steps
  #
  def init(p_seq_number=1)
    self.data_home = p_seq_number

    @param = 5 unless (@param)  # Default
    @state = READY
  end

  ##
  # Override execute.
  #
  def execute
    if (@state == READY)
      @state = EXECUTING
      for i in 1..@param
	syslog("_ Do this", i)
	raise OkToContinue.new("Sample exception! Continue plan...") if @exception
      end
      @state = FINISHED
    else
      syslog("_ Not ready to execute. Run init first, maybe?")
    end
  end

end


##
# Standalone unit test (recommended)
#
if __FILE__ == $0
  require 'rexml/document'
  require 'utils/misc'

  # Test code here
  # Typical subclassed behavior usage
  doc = REXML::Document.new(File.new(Misc.find_plan("test_sample.xml")))
  
  puts("Typical subclassed behavior usage")
  b = SampleBehavior.new(doc.elements[1])
  puts(b.dump)
  b.init
  b.execute
  b.abort
  sleep(1)
  
  puts("Done")
end
