module AE


  class Console



    # This module suggests completions a ruby code string from the live ObjectSpace
    # using Ruby's reflection methods. This way we get highly relevant suggestions
    # that not only match alphabetically to the inpu, but also to what is valid
    # in the current context.
    module Autocompleter
      require(File.join(File.dirname(__FILE__), "Introspection.rb"))

      # Returns a list of suggestions for a ruby code string
      # @param [String] string is the identifier before the current input
      # @param [String] prefix the current, half-completed input
      # @returns [Array<Hash>] suggestions
      def self.complete(string, prefix, context=nil)
        #
        methods_only =string.slice!(/(?:\.|\:\:)$/) == "."
        object = Introspection.get_object_from_string(string, context)
        list = []
        if object.respond_to?(:methods)
          list.concat object.methods.find_all{ |name| name[0...prefix.length] == prefix }
        end
        if !methods_only && object.respond_to?(:constants)
          list.concat object.constants.find_all{ |name| name[0...prefix.length] == prefix }
        end
        return list.map{ |word|
          {
            :name => word,
            :value => word,
            :score => 0,
            :meta => (object.is_a?(Module)) ? object.name : object.class.name
          }
        }
      end

    end


  end # Console


end # AE
