/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.lucene.sandbox.search;

import static org.apache.lucene.search.TopDocsCollector.EMPTY_TOPDOCS;

import java.io.IOException;
import java.util.List;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollectorManager;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.index.RandomIndexWriter;
import org.apache.lucene.tests.search.CheckHits;
import org.apache.lucene.tests.util.LuceneTestCase;

public class TestLargeNumHitsTopDocsCollector extends LuceneTestCase {
  private Directory dir;
  private IndexReader reader;
  private final Query testQuery =
      new BooleanQuery.Builder()
          .add(new TermQuery(new Term("field", "5")), BooleanClause.Occur.SHOULD)
          .add(MatchAllDocsQuery.INSTANCE, BooleanClause.Occur.SHOULD)
          .build();

  @Override
  public void setUp() throws Exception {
    super.setUp();
    dir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
    for (int i = 0; i < 1_000; i++) {
      Document doc = new Document();
      doc.add(newStringField("field", "5", Field.Store.NO));
      writer.addDocument(doc);
      writer.addDocument(new Document());
    }
    reader = writer.getReader();
    writer.close();
  }

  @Override
  public void tearDown() throws Exception {
    reader.close();
    dir.close();
    dir = null;
    super.tearDown();
  }

  public void testRequestMoreHitsThanCollected() throws Exception {
    runNumHits(150);
  }

  public void testSingleNumHit() throws Exception {
    runNumHits(1);
  }

  public void testRequestLessHitsThanCollected() throws Exception {
    runNumHits(25);
  }

  public void testInvalidRequestedHitCount() {
    for (int n : new int[] {0, -1}) {
      IllegalArgumentException e =
          expectThrows(IllegalArgumentException.class, () -> new LargeNumHitsTopDocsCollector(n));
      assertTrue(e.getMessage().contains("requestedHitCount must be > 0"));
    }
  }

  public void testHowMany() throws IOException {
    IndexSearcher searcher = newSearcher(reader);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(15);

    searcher.search(testQuery, largeCollectorManager);
    List<LargeNumHitsTopDocsCollector> collectorList = largeCollectorManager.getCollectors();
    LargeNumHitsTopDocsCollector largeCollector =
        collectorList.get(random().nextInt(0, collectorList.size()));

    IllegalArgumentException expected =
        expectThrows(IllegalArgumentException.class, () -> largeCollector.topDocs(-1));
    assertTrue(expected.getMessage().contains("Number of hits requested must not be negative"));

    assertEquals(EMPTY_TOPDOCS, largeCollector.topDocs(0));
    assertEquals(largeCollector.totalHits, largeCollector.topDocs(35_000).totalHits.value());
  }

  public void testNoPQBuild() throws IOException {
    IndexSearcher searcher = newSearcher(reader);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(250_000);
    TopScoreDocCollectorManager regularCollectorManager =
        new TopScoreDocCollectorManager(reader.numDocs(), Integer.MAX_VALUE);

    TopDocs largeTopDocs = searcher.search(testQuery, largeCollectorManager);
    TopDocs regularTopDocs = searcher.search(testQuery, regularCollectorManager);
    assertEquals(largeTopDocs.totalHits.value(), regularTopDocs.totalHits.value());

    for (LargeNumHitsTopDocsCollector largeCollector : largeCollectorManager.getCollectors()) {
      assertNull(largeCollector.pq);
      assertNull(largeCollector.pqTop);
    }
  }

  public void testPQBuild() throws IOException {
    IndexSearcher searcher = newSearcher(reader);
    int requestedHitCount = random().nextInt(1, 1000);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(requestedHitCount);
    TopScoreDocCollectorManager regularCollectorManager =
        new TopScoreDocCollectorManager(requestedHitCount, Integer.MAX_VALUE);

    TopDocs largeTopDocs = searcher.search(testQuery, largeCollectorManager);
    TopDocs regularTopDocs = searcher.search(testQuery, regularCollectorManager);
    assertEquals(largeTopDocs.totalHits.value(), regularTopDocs.totalHits.value());

    for (LargeNumHitsTopDocsCollector largeCollector : largeCollectorManager.getCollectors()) {
      if (largeCollector.totalHits > requestedHitCount) {
        assertNotNull(largeCollector.pq);
        assertNotNull(largeCollector.pqTop);
      }
    }
  }

  public void testNoPQHitsOrder() throws IOException {
    IndexSearcher searcher = newSearcher(reader);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(250_000);
    TopScoreDocCollectorManager regularCollectorManager =
        new TopScoreDocCollectorManager(reader.numDocs(), Integer.MAX_VALUE);

    TopDocs largeTopDocs = searcher.search(testQuery, largeCollectorManager);
    TopDocs regularTopDocs = searcher.search(testQuery, regularCollectorManager);
    assertEquals(largeTopDocs.totalHits.value(), regularTopDocs.totalHits.value());

    for (LargeNumHitsTopDocsCollector largeCollector : largeCollectorManager.getCollectors()) {
      assertNull(largeCollector.pq);
      assertNull(largeCollector.pqTop);
    }

    if (largeTopDocs.scoreDocs.length > 0) {
      float preScore = largeTopDocs.scoreDocs[0].score;
      for (ScoreDoc scoreDoc : largeTopDocs.scoreDocs) {
        assert scoreDoc.score <= preScore;
        preScore = scoreDoc.score;
      }
    }
  }

  public void testInvalidNumHitsInManagerConstructor() {
    for (int n : new int[] {0, -1}) {
      IllegalArgumentException e =
          expectThrows(
              IllegalArgumentException.class, () -> new LargeNumHitsTopDocsCollectorManager(n));
      assertTrue(e.getMessage().contains("numHits must be > 0"));
    }
  }

  public void testReduceWithZeroHitCollector() throws IOException {
    Query termQuery = new TermQuery(new Term("field", "no-hit"));

    IndexSearcher searcher = newSearcher(reader);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(50);
    TopScoreDocCollectorManager regularCollectorManager =
        new TopScoreDocCollectorManager(50, Integer.MAX_VALUE);

    TopDocs largeTopDocs = searcher.search(termQuery, largeCollectorManager);
    TopDocs regularTopDocs = searcher.search(termQuery, regularCollectorManager);

    assertEquals(largeTopDocs.totalHits.value(), regularTopDocs.totalHits.value());
    assertEquals(0, largeTopDocs.totalHits.value());
  }

  private void runNumHits(int numHits) throws IOException {
    IndexSearcher searcher = newSearcher(reader);
    LargeNumHitsTopDocsCollectorManager largeCollectorManager =
        new LargeNumHitsTopDocsCollectorManager(numHits);
    TopScoreDocCollectorManager regularCollectorManager =
        new TopScoreDocCollectorManager(numHits, Integer.MAX_VALUE);

    TopDocs largeTopDocs = searcher.search(testQuery, largeCollectorManager);
    TopDocs regularTopDocs = searcher.search(testQuery, regularCollectorManager);

    assertEquals(largeTopDocs.totalHits.value(), regularTopDocs.totalHits.value());
    assertEquals(largeTopDocs.scoreDocs.length, regularTopDocs.scoreDocs.length);
    CheckHits.checkEqual(testQuery, largeTopDocs.scoreDocs, regularTopDocs.scoreDocs);
  }
}
