package org.getopt.luke;

import org.apache.lucene.search.TimeLimitedCollector;
import org.apache.lucene.search.TopDocCollector;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TimeLimitedCollector.TimeExceededException;

public class IntervalLimitedCollector extends LimitedHitCollector {
  private long maxTime;
  private long lastDoc = 0;
  TopDocCollector tdc;
  TopDocs topDocs = null;
  TimeLimitedCollector thc;
  
  
  public IntervalLimitedCollector(int maxTime) {
    this.maxTime = maxTime;
    tdc = new TopDocCollector(1000);
    thc = new TimeLimitedCollector(tdc, maxTime);
  }

  /* (non-Javadoc)
   * @see org.getopt.luke.LimitedHitCollector#limitSize()
   */
  @Override
  public long limitSize() {
    return maxTime;
  }

  /* (non-Javadoc)
   * @see org.getopt.luke.LimitedHitCollector#limitType()
   */
  @Override
  public int limitType() {
    return TYPE_TIME;
  }

  @Override
  public int getDocId(int pos) {
    if (topDocs == null) {
      topDocs = tdc.topDocs();
    }
    return topDocs.scoreDocs[pos].doc;
  }

  /* (non-Javadoc)
   * @see org.getopt.luke.AccessibleHitCollector#getScore(int)
   */
  @Override
  public float getScore(int pos) {
    if (topDocs == null) {
      topDocs = tdc.topDocs();
    }
    return topDocs.scoreDocs[pos].score;
  }

  @Override
  public int getTotalHits() {
    return tdc.getTotalHits();
  }

  @Override
  public void collect(int docNum, float score) {
    try {
      thc.collect(docNum, score);
    } catch (TimeExceededException tee) {
      // re-throw
      throw new LimitedException(TYPE_TIME, maxTime, tee.getTimeElapsed(), tee.getLastDocCollected());
    }
  }
}
