#---
# 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 RulesBuilder22
  def load aStream
    @config = Configuration.new
    data = eval aStream.join("\n")
    config data
    return @config
  end
  
  def config args
    args[:items].each {|i| process_item i}
  end

  def process_item hash
    puts hash
    newItem = Item.new hash[:id]
    process_item_args(newItem, hash)
    @config.add_item newItem
    return self
  end

  def process_item_args anItem, args
    args.each_pair do |key, value|
      case key
      when :item
        #ignore
      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
  RulesBuilder22.new.load(File.readlines('rules22.rb'))
end

