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

import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;

/**
 * @author jochen
 *
 */
public class LogReader extends AbstractIndexReader{

	private static final Log log = LogFactory.getLog(Log.class);
	
//	public String getLogRecord(String instanceId) throws IOException{
//		getResults(getQuery(LogWriter.fieldId, instanceId));
//		return null;
//	}
	
	private Query getQuery(String field, String value){
		return new TermQuery(new Term(LogWriter.fieldId, value));
	}
	
	private List<LogInfo> getResults(Query query) throws IOException{
   		List<LogInfo> list = new LinkedList<LogInfo>();
		TopDocs td = searcher.search(query, null, 1000);
		log.debug("total hits of logs: " + td.totalHits);
		ScoreDoc[] hits = td.scoreDocs;
		for (ScoreDoc sd: Arrays.asList(hits)){
			Document doc = searcher.doc(sd.doc);
			LogInfo li = new LogInfo();
			li.setInstanceId(doc.get(LogWriter.fieldId));
			li.setTimeStamp(Long.valueOf(doc.get(LogWriter.fieldTimestamp)));
			Properties props = new Properties();
			props.load(new StringReader(doc.get(LogWriter.fieldLogProperties)));
			li.setLogProperties(props);
			list.add(li);
		}
		searcher.close();
		return list;
	}
	
	public List<LogInfo> getLogRecordInRange(String instanceId, String from, String to) throws IOException{
   		
		TermRangeQuery tq = new TermRangeQuery(LogWriter.fieldTimestamp, from, to, true, true);
		
		BooleanQuery bq = new BooleanQuery();
		bq.add(getQuery(LogWriter.fieldId, instanceId), BooleanClause.Occur.MUST);
		bq.add(tq, BooleanClause.Occur.MUST);
		return getResults(bq);
	}

}
