package cn.com.pc.penguin.core;

import cn.com.pc.penguin.service.PenguinSearchResults;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;

import java.io.IOException;
import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * User: huangqinghe
 * To change this template use File | Settings | File Templates.
 */
public class PenguinSearchManager implements SearchManager{
    private PenguinIndexer indexer;
	private PenguinSearcher searcher;
	private PenguinSettings settings;

	public PenguinSettings getSettings() {
		return settings;
	}

	public void setSettings(PenguinSettings settings) {
		this.settings = settings;
	}

	public void init() throws Exception {
		searcher = new PenguinSearcher(settings);
		indexer = new PenguinIndexer(settings);
		indexer.watchNewDocuDocumentAdded(searcher);

		new Thread(new NotifyWorker()).start();

	}

	public void removeLockFile() throws Exception {
		try {
			if (IndexWriter.isLocked(this.settings.directory())) {
				IndexWriter.unlock(this.settings.directory());
			}
		} catch (IOException e) {
			throw e;
		}
	}

	public void notifyNewDocumentAdded() throws Exception {
		this.indexer.notifyNewDocumentAdded();
	}

	public void commit() throws Exception {
		this.indexer.commit();
	}

	public void createIndex(Document doc) throws Exception {
		this.indexer.createIndex(doc);
	}

	public PenguinSearchResults search(PenguinArgs args) throws Exception {
		PenguinSearchResults results = this.searcher.search(args);
        //save keyword later
        return results;
	}

	public void delete(String id) throws Exception {
		this.indexer.delete(id);
	}

	public void createIndex(Collection<Document> docs, Collection<String> ids)
			throws Exception {
		this.indexer.createIndex(docs, ids);
	}

	public void delete(Collection<String> ids) throws Exception {
		this.indexer.delete(ids);
	}

	class NotifyWorker implements Runnable {

		public NotifyWorker() {
		}

		public void run() {
			while (true) {
				try {
					Thread.sleep(5000);
					indexer.notifyNewDocumentAdded();
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
		}
	}
}
