# encoding: utf-8

module XapianDb

  # The indexer creates a Xapian::Document from an object. They object must be an instance
  # of a class that has a blueprint configuration.
  # @author Gernot Kogler
  class Indexer

    # Constructor
    # @param [XapianDb::Database] database The database to use (needed to build a spelling index)
    # @param [XapianDb::DocumentBlueprint] document_blueprint The blueprint to use
    def initialize(database, document_blueprint)
      @database, @document_blueprint = database, document_blueprint
    end

    # Build the document for an object. The object must respond to 'xapian_id'.
    # The configured adapter should implement this method.
    # @return [Xapian::Document] The xapian document (see http://xapian.org/docs/sourcedoc/html/classXapian_1_1Document.html)
    def build_document_for(obj)
      @obj = obj
      @blueprint = DocumentBlueprint.blueprint_for(@obj.class)
      @xapian_doc = Xapian::Document.new
      @xapian_doc.data = @obj.xapian_id
      store_fields
      index_text
      @xapian_doc
    end

    private

    # Store all configured fields
    def store_fields

      # We store the class name of the object at position 0
      @xapian_doc.add_value(0, @obj.class.name)

      @blueprint.attribute_names.each do |attribute|
        block = @blueprint.block_for_attribute attribute
        if block
          value = @obj.instance_eval(&block)
        else
          value = @obj.send(attribute)
        end
        @xapian_doc.add_value(@blueprint.value_index_for(attribute), value.to_yaml)
      end
    end

    # Index all configured text methods
    def index_text
      setup_language_helpers
      term_generator = Xapian::TermGenerator.new
      term_generator.database = @database.writer
      term_generator.document = @xapian_doc
      if @stemmer
        term_generator.stemmer  = @stemmer
        term_generator.stopper  = @stopper unless @stopper.nil?
        # Enable the creation of a spelling dictionary if the database is not in memory
        term_generator.set_flags Xapian::TermGenerator::FLAG_SPELLING if @database.is_a? XapianDb::PersistentDatabase
      end

      # Index the primary key as a unique term
      @xapian_doc.add_term("Q#{@obj.xapian_id}")

      # Index the class with the field name
      term_generator.index_text("#{@obj.class}".downcase, 1, "XINDEXED_CLASS")
      @xapian_doc.add_term("C#{@obj.class}")


      # @blueprint.indexed_methods_hash.keys.sort.each do |method|
      #   options = @blueprint.indexed_methods_hash[method]
      #   if options.block
      #     obj = @obj.instance_eval(&options.block)
      #   else
      #     obj = @obj.send(method)
      #   end
      #   unless obj.nil?
      #     values = get_values_to_index_from obj
      #     values.each do |value|
      #       # Add value with field name
      #       term_generator.index_text(value.to_s.downcase, options.weight, "X#{method.upcase}")
      #       # Add value without field name
      #       term_generator.index_text(value.to_s.downcase)
      #     end
      #   end
      # end

      @blueprint.indexed_method_names.each do |method|
        options = @blueprint.options_for_indexed_method method
        if options.block
          obj = @obj.instance_eval(&options.block)
        else
          obj = @obj.send(method)
        end
        unless obj.nil?
          values = get_values_to_index_from obj
          values.each do |value|
            # Add value with field name
            term_generator.index_text(value.to_s.downcase, options.weight, "X#{method.upcase}")
            # Add value without field name
            term_generator.index_text(value.to_s.downcase)
          end
        end
      end

    end

    private

    # Configure the stemmer and stopper to use
    def setup_language_helpers
      # Do we have a language config on the blueprint?
      if @blueprint.lang_method
        lang = @obj.send(@blueprint.lang_method)
        if lang && LANGUAGE_MAP.has_key?(lang.to_sym)
          @stemmer = XapianDb::Repositories::Stemmer.stemmer_for lang.to_sym
          @stopper = XapianDb::Repositories::Stopper.stopper_for lang.to_sym
          return
        end
      end

      # Use the global config
      @stemmer = XapianDb::Config.stemmer
      @stopper = XapianDb::Config.stopper

    end

    # Get the values to index from an object
    def get_values_to_index_from(obj)

      # if it's an array, that's fine
      return obj if obj.is_a? Array

      # if the object responds to attributes and attributes is a hash,
      # we use the attributes values (works well for active_record and datamapper objects)
      return obj.attributes.values if obj.respond_to?(:attributes) && obj.attributes.is_a?(Hash)

      # The object is unkown and will be indexed by its to_s method
      return [obj]
    end

  end

end