/**
 * 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.hadoop.hbase.hbtop.mode;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.hadoop.hbase.hbtop.Record;
import org.apache.hadoop.hbase.hbtop.RecordFilter;
import org.apache.hadoop.hbase.hbtop.field.Field;

public final class ModeStrategyUtils {
  private ModeStrategyUtils() {

  }

  /**
   * Filter records as per the supplied filters,
   * @param records records to be processed
   * @param filters List of filters
   * @return filtered records
   */
  public static List<Record> applyFilterAndGet(List<Record> records,
      List<RecordFilter> filters) {
    if (filters != null && !filters.isEmpty()) {
      return records.stream().filter(r -> filters.stream().allMatch(f -> f.execute(r)))
          .collect(Collectors.toList());
    }
    return records;
  }


  /**
   * Group by records on the basis of supplied groupBy field and
   * Aggregate records using {@link Record#combine(Record)}
   *
   * @param records records needs to be processed
   * @param groupBy Field to be used for group by
   * @return aggregated records
   */
  public static List<Record> aggregateRecords(List<Record> records, Field groupBy) {
    return records.stream().collect(Collectors.groupingBy(r -> r.get(groupBy))).entrySet().stream()
        .flatMap(e -> e.getValue().stream().reduce(Record::combine).map(Stream::of)
            .orElse(Stream.empty())).collect(Collectors.toList());
  }

}
