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

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.Assert;


/**
 * @author jochen
 *
 */
public class LogInfoService extends AbstractInfoService{

	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

   	
   	public synchronized void persist(LogInfo logInfo) throws CorruptIndexException, LockObtainFailedException, IOException{
   		LogWriter writer = new LogWriter();
   		Assert.assertNotNull(dir);
		writer.init(dir, create);
   		writer.store(logInfo.getInstanceId(), logInfo.getTimeStamp() + "", logInfo.getLogProperties());
   		create = false;
   	}
   	
   	public List<LogInfo> findLogInfos(String instanceId, long from, long to) throws CorruptIndexException, IOException{
   		List<LogInfo> list = new LinkedList<LogInfo>();
   		if (create){
   			// no logEntries exist, because there is no index-directory with files in it.
   			return list;
   		}
   		LogReader reader = new LogReader();
   		reader.init(dir);
   		return reader.getLogRecordInRange(instanceId, from + "", to + "");
   	}

   	public static String getDate(long timestamp){
   		return sdf.format(new Date(timestamp));
   	}

}
