#!/usr/local/bin/ruby -w
require 'fileutils'
require 'test/unit'
require 'tmpdir'
require 'rsi'
require 'rsi/logmanager'

DOC_A = "The quick brown fox jumped over the lazy dogs"
DOC_B = "Every dog has his day"
DOC_C = "Bjork, bjork, were you brought by the stork, or were you" +
  " created from bubbles and cork?"

class IdxTest < Test::Unit::TestCase

  # Create a temp dir for the indexes in the test
  def setup()
    @tmp = Dir::tmpdir()
    @root = File.join( @tmp, "searchtest.#{$$}.#{rand(65535)}" )
    Dir.mkdir( @root ) # will raise if root exists, which is what I want
    @failed = false
  end

  def add_failure( msg, bt )
    super
    @failed = true
  end

  # Delete the temp dir for the index tests
  def teardown()
    if @failed
      print "Test case failed, not cleaning up #@root\n";
    else
      FileUtils::rm_rf( @root )
    end
  end

  # Create an index, assert that it contains the right docs and terms
  def test_basic()
    indexer = RSI::Indexer.new( @root )
    indexer.serializer = RSI::YAMLSerializer.new()
    indexer.open()
    indexer.add_document( "DOC_A", DOC_A )
    indexer.add_document( "DOC_B", DOC_B )
    indexer.add_document( "DOC_C", DOC_C )
    indexer.flush()
    assert_finds( indexer )
  end

  # Creates an index, then asserts that it can be re-opened
  def __SKIP__test_reopen()
    test_basic() # build index with 3 docs
    indexer = RSI::Indexer.new( @root )
    indexer.serializer = RSI::YAMLSerializer.new()
    indexer.open()
    assert_finds( indexer )
  end

  # Assert that the given index contains the right documents/terms
  def assert_finds( indexer )
    a = indexer.find_all( "Bjork" )
    assert_equal( 1, a.length(), "Should have one hit (DOC_C)" )
    assert_equal( "DOC_C", a[0], "Should find DOC_C" )

    a = indexer.find_all( "bjork" )
    assert_equal( 1, a.length(), "(+i) Should have one hit (DOC_C)" )
    assert_equal( "DOC_C", a[0], "(+i) Should find DOC_C" )

    a = indexer.find_all( "dog" )
    assert_equal( 2, a.length(), "Should have two hits (DOC_A, DOC_B)" )
  end

end

if $0 == __FILE__
  RSI::LogManager.instance.root = "."
  RSI::LogManager.instance.log_filename = "t_index.log"
end