/**
 * 
 */
package eu.dnetlib.data.collective.manager.log;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Properties;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.NIOFSDirectory;

/**
 * @author js
 *
 */
public class AbstractIndexReader {
	protected IndexSearcher searcher;

	/**
	 * @param indexDirectory
	 * @throws CorruptIndexException
	 * @throws IOException
	 */
	public void init(File indexDirectory) throws CorruptIndexException, IOException{
		IndexReader reader = IndexReader.open(NIOFSDirectory.open(indexDirectory), true);
		searcher = new IndexSearcher(reader);
	}
	
	/**
	 * get the properties stored in the index identified by the given argument
	 * @param aIdentifier
	 * @return properties
	 * @throws IOException
	 */
	public Properties getProperties(String aIdentifier) throws IOException{
		TopDocs td = searcher.search(new TermQuery(new Term(GenericInfoWriter.fieldId, aIdentifier)), null, 1);
		ScoreDoc[] hits = td.scoreDocs;
		Properties props = new Properties();
		for (ScoreDoc sd: Arrays.asList(hits)){
			Document doc = searcher.doc(sd.doc);
			props.load(new StringReader(doc.get(GenericInfoWriter.fieldProperties)));
			break;
		}
		searcher.close();
		return props;
	}

}
