package com.search.lucene.searchers.implementations;

import java.io.IOException;
import java.nio.file.Paths;

import com.search.lucene.documents.representers.abstractions.IDocumentRepresenter;
import com.search.lucene.searchers.abstractions.ISearcher;
import com.search.lucene.settings.Constants;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexedDocumentSearcher implements ISearcher {


    private IndexSearcher indexSearcher;
    private QueryParser queryParser;
    private final String indexDirectoryPath;
    private final String queryForField;

    public IndexedDocumentSearcher(String indexDirectoryPath, String queryForField)
            throws IOException {
        this.indexDirectoryPath = indexDirectoryPath;
        this.queryForField = queryForField;
    }


    @Override
    public TopDocs search(String searchQuery)
            throws IOException, ParseException {
        Query query = queryParser.parse(searchQuery);
        return indexSearcher.search(query, Constants.MAX_SEARCH);
    }

    @Override
    public void init() throws IOException {
        Directory indexDirectory = FSDirectory.open(Paths.get(indexDirectoryPath));
        IndexReader reader = DirectoryReader.open(indexDirectory);
        indexSearcher = new IndexSearcher(reader);
        queryParser = new QueryParser(queryForField, new StandardAnalyzer());
    }

    @Override
    public Document getDocument(ScoreDoc scoreDoc)
            throws CorruptIndexException, IOException {
        return indexSearcher.doc(scoreDoc.doc);
    }
}