#---
# Excerpted from "The ThoughtWorks Anthology",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material, 
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose. 
# Visit http://www.pragmaticprogrammer.com/titles/twa for more book information.
#---

require 'model'
#require 'breakpoint'

class RulesBuilder5
  def load aStream
    @config = Configuration.new
    instance_eval aStream.join("\n")
    return @config
  end

  def item name, *args
    newItem = Item.new name
    process_item_args(newItem, args) unless args.empty?
    @config.add_item newItem
    return self
  end

  def process_item_args anItem, args
    args[0].each_pair do |key, value|
      case key
      when :depends_on
        oneOrMany(value) {|i| anItem.add_dependency(@config[i])}
      when :uses
        oneOrManyTerms(value) {|r| anItem.add_usage(parse_resource(r))}
      when :provides
        oneOrManyTerms(value) {|r| anItem.add_provision(parse_resource(r))}
      end
    end
  end
  
  def parse_resource r
    case r[0]
    when :electricity
      result = Electricity.new(r[1])
    when :acid
      result = Acid.new
      result.type = r[1][:type]
      result.grade = r[1][:grade]
    end
    return result
  end
  def oneOrMany(obj, &block)
    if obj.kind_of? Array
      obj.each(&block)
    else
      yield obj
    end
  end


  def oneOrManyTerms(obj, &block)
    if obj[0].kind_of? Array
      obj.each(&block)
    else
      yield obj
    end
  end

end


if __FILE__ == $0
  RulesBuilder5.new.load(File.readlines('rules5.rb'))
end

