class ConstantAlreadyExistsError < RuntimeError
end

class Object
  # include the class specified by +include_class+ into the current namespace,
  # using either its base name or by using a name returned from an optional block,
  # passing all specified classes in turn and providing the block package name
  # and base class name.
  def include_class(include_class)
    if include_class.respond_to? "java_class"
      # FIXME: When I changed this user const_set instead of eval below Comparator got lost
      # which means I am missing something.
      constant = include_class.java_class.to_s.split(".").last
      if (respond_to?(:class_eval, true))
        return class_eval("#{constant} = #{include_class.java_class}")
      else
        return eval("#{constant} = #{include_class.java_class}")
      end
    end
    
    if include_class.respond_to? "_name"
      return self.class.instance_eval { import(include_class._name) };
    end
    
    # else, pull in the class
    class_names = include_class.to_a

    class_names.each do |full_class_name|
      package_name, class_name = full_class_name.match(/((.*)\.)?([^\.]*)/)[2,3]

      if block_given?
        constant = yield(package_name, class_name)
      else
        constant = class_name
      end
      
      cls = self.kind_of?(Module) ? self : self.class

	  # Constant already exists...do not let proxy get created unless the collision is the proxy
	  # you are trying to include.
      if (cls.const_defined?(constant) )
        proxy = JavaUtilities.get_proxy_class(full_class_name)
        existing_constant = cls.const_get(constant)
      	raise ConstantAlreadyExistsError.new, "Class #{constant} already exists" unless existing_constant == proxy
	  end

      # FIXME: When I changed this user const_set instead of eval below Comparator got lost
      # which means I am missing something.
      if (respond_to?(:class_eval, true))
        class_eval("#{constant} = JavaUtilities.get_proxy_class(\"#{full_class_name}\")")
      else
        eval("#{constant} = JavaUtilities.get_proxy_class(\"#{full_class_name}\")")
      end
    end
  end
  
  # TODO: this can go away now, but people may be using it
  def java_kind_of?(other)
    return true if self.kind_of?(other)
    return false unless self.respond_to?(:java_class) && other.respond_to?(:java_class) &&
      other.kind_of?(Module) && !self.kind_of?(Module) 
    return other.java_class.assignable_from?(self.java_class)
  end
  
  alias :import :include_class
  private :import
end
