/*
 * 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.sentiment;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import opennlp.tools.util.FilterObjectStream;
import opennlp.tools.util.ObjectStream;

/**
 * Class for creating a type filter.
 *
 * @see FilterObjectStream
 * @see SentimentSample
 */
public class SentimentSampleTypeFilter
    extends FilterObjectStream<SentimentSample, SentimentSample> {

  private final Set<String> types;

  /**
   * Constructor
   */
  public SentimentSampleTypeFilter(String[] types, ObjectStream<SentimentSample> samples) {
    super(samples);
    this.types = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(types)));
  }

  /**
   * Instantiates a {@link SentimentSampleTypeFilter} object.
   *
   * @param types
   *          the types to filter.
   * @param samples
   *          the sentiment samples to be used.
   */
  public SentimentSampleTypeFilter(Set<String> types, ObjectStream<SentimentSample> samples) {
    super(samples);
    this.types = Set.copyOf(types);
  }

  /**
   * @return Reads and returns the next {@link SentimentSample} whose sentiment
   *         matches the configured types, or {@code null} if the stream is exhausted.
   */
  @Override
  public SentimentSample read() throws IOException {
    SentimentSample sample;
    while ((sample = samples.read()) != null) {
      if (types.contains(sample.getSentiment())) {
        return sample;
      }
    }
    return null;
  }

}
