#---
# 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 RulesBuilder6
  def load aStream
    @config = Configuration.new
    data = eval aStream.join("\n")
    config data
    return @config
  end

  def config list
    list.each do |e| 
      case e.head
      when :item
        build_item e.tail
      else raise 
      end
    end
  end

  def build_item list
    newItem = Item.new list.head
    @config.add_item newItem
    list.tail.each {|l| process_item_args newItem, l} if list.tail
  end
  

  def process_item_args anItem, args
    unless 2 <= args.length
      puts "args: %s" % args
      exit
    end
    case args.head
    when :depends_on
      args.tail.each {|i| anItem.add_dependency @config[i]}
    when :uses
      args.tail.each {|r| anItem.add_usage(parse_resource(r))}
    when :provides
      args.tail.each {|r| anItem.add_provision(parse_resource(r))}
    else raise 
    end
  end

  def parse_resource r
    case r.head
    when :electricity
      result = Electricity.new(r[1])
    when :acid
      result = Acid.new
      process_acid(result, r.tail)
    else raise
    end
    return result
  end
  def process_acid acid, args
    args.each do |arg|
      case arg.head
      when :type
        acid.type = arg[1]
      when :grade
        acid.grade = arg[1]
      else raise
      end
    end
  end

end

class Array
  def tail
    self[1..-1]
  end
  alias head first
end


if __FILE__ == $0
  RulesBuilder6.new.load(File.readlines('rules6.rb'))
end

