package com.search.lucene.engine.implementations;

import com.search.lucene.engine.abstractions.ISearchEngine;
import com.search.lucene.indexers.abstractions.IFileIndexer;
import com.search.lucene.searchers.abstractions.ISearcher;
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;

import java.io.IOException;
import java.util.ArrayList;

public class LuceneEngine implements ISearchEngine {
    private final ArrayList<IFileIndexer> indexers;
    private final ArrayList<ISearcher> searchers;

    public LuceneEngine(ArrayList<IFileIndexer> indexers, ArrayList<ISearcher> searchers) {
        this.indexers = indexers;
        this.searchers = searchers;
    }

    @Override
    public void createIndexesForDirectory(String directoryPath) throws IOException {
        for (IFileIndexer indexer : indexers) {
            System.out.println("Starting indexing " + indexer.getClass().getName());
            indexer.createIndex(directoryPath);
            indexer.close();
        }
    }

    @Override
    public ArrayList<Document> search(String searchQuery) throws IOException, ParseException {
        ArrayList<Document> documents = new ArrayList<>();
        for (ISearcher searcher : searchers) {
            searcher.init();
            TopDocs hits = searcher.search(searchQuery);

            for(ScoreDoc scoreDoc : hits.scoreDocs) {
                documents.add(searcher.getDocument(scoreDoc));
            }
        }
        return documents;
    }
}
