##############################################################################
# ConfigMan - load mission config file and serve-up the values by name
#
#  23-May-07 RGH => Initial development, very simple document layout and
#                   server. Exceptions are caught during the load method
#                   and are not propagated.
#
##############################################################################

require 'rexml/document'    # Ruby XML library

class ConfigMan
  include REXML

  # Constructor takes a configuration filename (string)
  #
  def initialize filename=""
    @filename = filename
    @file = nil
    @err = nil
  end

  # Change the configuration file used by ConfigMan object
  # Remember to call load again
  #
  def configfile=newfile
    @filename = newfile
  end
  
  def configfile
    @filename
  end
  
  def last_error
    @err
  end
  
  # Load method opens and parses the configuration file
  # Returns nil if file could not be opened or parsed
  # without error, otherwise true. If nil, the exception
  # raised can be calling last_error
  #
  def load
    return nil unless @filename
    begin
      file = File.new(@filename)
      @xml = Document.new(file)
      @err = nil
      true
            
    rescue Exception
      @err = $!
      nil
    end
  end

  # Get method returns the value for the given element.
  # Takes a string argument element name.
  # Returns nil if element could not be found
  # otherwise the string value found in the config file.
  #
  def get(elem_name, attr_name="value")
    return nil unless @xml && @xml.root

    # Use the pattern-matching feature in the 'each' method
    # Relies on the fact that all the elements with values are
    # in the 3rd level and have unique names, which allows us to
    # use "*/*/name" as the pattern. Grab the given attribute.
    #
    @xml.elements.each("*/*/" + elem_name) { |e| @val = e.attributes[attr_name] }
    @val
  end
  
end

