/*
 * Copyright 2004 The Apache Software Foundation
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using NUnit.Framework;
/*using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;*/
namespace clucene.net
{
	
	
	/// <author>  goller
	/// </author>
	/// <version>  $Id: TestIndexWriter.cs,v 1.3 2006/01/11 05:15:07 ustramooner Exp $
	/// </version>
    [TestFixture]
    public class TestIndexWriter
	{
        [Test]
		public virtual void  TestDocCount()
		{
			Directory dir = new RAMDirectory();
			
			IndexWriter writer = null;
			IndexReader reader = null;
			int i;
			
			try
			{
				writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true);
				
				// add 100 documents
				for (i = 0; i < 100; i++)
				{
					AddDoc(writer);
				}
				Assert.AreEqual(100, writer.docCount());
				writer.close();
				
				// delete 40 documents
				reader = IndexReader.open(dir);
				for (i = 0; i < 40; i++)
				{
					reader.Delete(i);
				}
				reader.close();
				
				// test doc count before segments are merged/index is optimized
				writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false);
				Assert.AreEqual(100, writer.docCount());
				writer.close();
				
				reader = IndexReader.open(dir);
				Assert.AreEqual(100, reader.maxDoc());
				Assert.AreEqual(60, reader.numDocs());
				reader.close();
				
				// optimize the index and check that the new doc count is correct
				writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false);
				writer.optimize();
				Assert.AreEqual(60, writer.docCount());
				writer.close();
				
				// check that the index reader gives the same numbers.
				reader = IndexReader.open(dir);
				Assert.AreEqual(60, reader.maxDoc());
				Assert.AreEqual(60, reader.numDocs());
				reader.close();
			}
			catch (System.IO.IOException e)
			{
                System.Console.Error.WriteLine(e.StackTrace);
			}
		}
		
		private void  AddDoc(IndexWriter writer)
		{
			Document doc = new Document();
			doc.add(Field.UnStored("content", "aaa"));
			
			try
			{
				writer.addDocument(doc);
			}
			catch (System.IO.IOException e)
			{
				System.Console.Error.WriteLine(e.StackTrace);
			}
		}
	}
}