/*
 * 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 opennlp.tools.util.featuregen;

import java.util.List;
import java.util.Objects;

import opennlp.tools.namefind.TokenNameFinder;
import opennlp.tools.util.Span;

/**
 * Generates features if the tokens are recognized by the provided
 * {@link TokenNameFinder}.
 */
public class InSpanGenerator implements AdaptiveFeatureGenerator {

  private final String prefix;

  private final TokenNameFinder finder;

  private String[] currentSentence;

  private Span[] currentNames;

  /**
   * Initializes the current instance.
   *
   * @param prefix the prefix is used to distinguish the generated features
   *     from features generated by other instances of {@link InSpanGenerator}s.
   * @param finder the {@link TokenNameFinder} used to detect the names.
   */
  public InSpanGenerator(String prefix, TokenNameFinder finder) {
    this.prefix = Objects.requireNonNull(prefix, "prefix must not be null");
    this.finder = Objects.requireNonNull(finder, "finder must not be null");
  }

  public void createFeatures(List<String> features, String[] tokens, int index,
      String[] preds) {
    // cache results for sentence
    if (currentSentence != tokens) {
      currentSentence = tokens;
      currentNames = finder.find(tokens);
    }

    // iterate over names and check if a span is contained
    for (Span currentName : currentNames) {
      if (currentName.contains(index)) {
        // found a span for the current token
        features.add(prefix + ":w=dic");
        features.add(prefix + ":w=dic=" + tokens[index]);

        // TODO: consider generation start and continuation features

        break;
      }
    }
  }
}
