package org.apache.lucene.search;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Lucene" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Lucene", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.IOException;
import org.apache.lucene.index.TermDocs;

final class TermScorer extends Scorer {
  private TermDocs termDocs;
  private byte[] norms;
  private float weight;
  private int doc;

  private static final int BUFFER_SIZE = 128;
  private static final int[] SENTINEL = {Integer.MAX_VALUE};

  private int[] docs;                             // buffered doc numbers
  private  int[] freqs;                           // buffered term freqs

  private int pointer;                            // pointer into buffers
  private int pointerMax;                         // end of buffers

  private static final int SCORE_CACHE_SIZE = 32;
  private float[] scoreCache = new float[SCORE_CACHE_SIZE];

  TermScorer(TermDocs td, int docFreq, byte[] n, float w) throws IOException {
    termDocs = td;
    norms = n;
    weight = w;

    for (int i = 0; i < SCORE_CACHE_SIZE; i++)
      scoreCache[i] = Similarity.tf(i) * weight;

    // minimize buffer sizes
    int bufferSize = (docFreq < BUFFER_SIZE) ? (docFreq+1) : BUFFER_SIZE;
    docs = new int[bufferSize];
    freqs = new int[bufferSize];

    refill();

  }

  private void refill() throws IOException {
    if (termDocs != null) {
      pointerMax = termDocs.read(docs, freqs);    // try to fill buffers
      if (pointerMax < docs.length) {             // read last into buffers
        termDocs.close();                         // close stream
        termDocs = null;                          // gc stream's buffer
      }
    } else {
      pointerMax = 0;
    }

    if (pointerMax == 0) {                        // last buffer consumed
      docs = SENTINEL;                            // gc docs, set sentinel
      freqs = null;                               // gc freqs
    }
    pointer = 0;
    doc = docs[pointer];
  }

  final void score(HitCollector c, final int end) throws IOException {
    int d = doc;				  // cache doc in local
    while (d < end) {				  // for docs in window
      final int f = freqs[pointer];
      float score =				  // compute tf(f)*weight
	f < SCORE_CACHE_SIZE			  // check cache
	 ? scoreCache[f]			  // cache hit
	 : Similarity.tf(f)*weight;		  // cache miss

      byte normByte = norms[d];
      if (normByte != 0) {                        // if not deleted
        score *= Similarity.norm(normByte);	  // normalize for field
        c.collect(d, score);			  // collect score
      }

      if (++pointer == pointerMax)
        refill();

      d = docs[pointer];
    }
    doc = d;					  // flush cache
  }
}

