/**
 * Copyright 2008-2009 DRIVER PROJECT (Bielefeld University)
 * Original author: Marek Imialek <marek.imialek at uni-bielefeld.de>
 *
 * 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.
 */
package eu.dnetlib.miscutils.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.CheckIndex;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.CheckIndex.Status;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * The Class CheckIndexHealth is used to check the health of an index 
 * and write a new segments file that removes reference to problematic segments.
 * Please notice that on a large index it can take quite a long time to run.
 * 
 * @author <a href="mailto:marek.imialek at uni-bielefeld.de">Marek Imialek</a> 
 */
public class CheckIndexHealth {

	/** The index. */
	private CheckIndex index;

	/** The status. */
	private Status status;

	/** The dir. */
	private Directory dir; 
	
	/**
	 * Instantiates a new CheckIndexHealth class.
	 * 
	 * @param luceneIndexDirectory source lucene index directory
	 * 
	 * @throws Exception the exception
	 */
	public CheckIndexHealth(String luceneIndexDirectory) throws Exception{
		
		
		File file = new File(luceneIndexDirectory);
	
		if(!file.exists())
			throw new Exception ("Can not find Lucene index at: "+luceneIndexDirectory);
		
		 dir = (Directory) FSDirectory.open(file);
		 
		 index = new CheckIndex(dir);
		 status = index.checkIndex();
		 
		 if (status.toolOutOfDate)
			 throw new Exception ("The index was created with a newer version of Lucene than the CheckIndex tool.");
	}
	
	/**
	 * Checks if index is health.
	 * 
	 * @return true, if is health
	 */
	public boolean isHealth() {
		return status.clean;
	}

	/**
	 * Repair broken index.
	 * 
	 * @throws Exception the exception
	 */
	public void repairIndex() throws Exception{
		try {
			if (this.isLocked())
				throw new Exception ("Index is locked other process.");
			index.fixIndex(status);
		} catch (IOException e) {
			throw new Exception ("Could not repair index: "+ status.dir +" : " +e);
		}
	}
	
	/**
	 * Checks if index is locked by other process
	 * 
	 * @return true, if is locked
	 * @throws Exception 
	 */
	public boolean isLocked() throws Exception {
		 try {
			return IndexWriter.isLocked(dir);
		} catch (IOException e) {
			throw new Exception(e);
		}
	}
	
}
