package com.search.lucene;

import java.io.IOException;

import com.search.lucene.file.filters.TextFileFilter;
import com.search.lucene.indexers.TextFileIndexer;
import com.search.lucene.searchers.Searcher;
import com.search.lucene.settings.LuceneConstants;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

public class Lucene {

    private static final String indexDir = "index";
    private static final String dataDir = "data";
    private static TextFileIndexer indexer;
    private static Searcher searcher;

    public static void main(String[] args) {
        try {
            createIndex();
            search("Kota");
            search("s");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private static void createIndex() throws IOException {
        indexer = new TextFileIndexer(indexDir);
        int numIndexed;
        long startTime = System.currentTimeMillis();
        numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
        long endTime = System.currentTimeMillis();
        indexer.close();
        System.out.println(numIndexed+" File indexed, time taken: "
                +(endTime-startTime)+" ms");
    }

    private static void search(String searchQuery) throws IOException, ParseException {
        searcher = new Searcher(indexDir);
        long startTime = System.currentTimeMillis();
        TopDocs hits = searcher.search(searchQuery);
        long endTime = System.currentTimeMillis();

        System.out.println(hits.totalHits +
                " documents found. Time :" + (endTime - startTime));
        for(ScoreDoc scoreDoc : hits.scoreDocs) {
            Document doc = searcher.getDocument(scoreDoc);
            System.out.println("File: "
                    + doc.get(LuceneConstants.FILE_PATH));
        }
    }
}
