package de.ivu.elect.jee.performance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class ViewAccessTargetStatistics extends ViewAccessTarget {

  private final long count;

  private final long timeTotal;

  public ViewAccessTargetStatistics(ViewAccessTarget target, long count, long timeTotal) {
    super(target);
    this.count = count;
    this.timeTotal = timeTotal;
  }

  public long getCount() {
    return count;
  }

  public long getTimeTotal() {
    return timeTotal;
  }

  @Override
  public String toString() {
    return "ViewAccessTargetStatistics{" +
        "count=" + count +
        ", timeTotal=" + timeTotal +
        "} " + super.toString();
  }

  public long getAverage() {
    if (count == 0) {
      return 0;
    }
    return Math.round((timeTotal * 1d) / count);
  }

  public static List<ViewAccessTargetStatistics> gruppiere(List<ViewAccessTargetStatistics> statistics, Function<ViewAccessTarget, ViewAccessTarget> copyKey) {
    Map<ViewAccessTarget, ViewAccessTargetStatistics> resultMap = new HashMap<>();

    for (ViewAccessTargetStatistics statistic : statistics) {
      ViewAccessTarget target = copyKey.apply(statistic);
      ViewAccessTargetStatistics tmp = resultMap.computeIfAbsent(target, x -> new ViewAccessTargetStatistics(target, 0L, 0L));
      resultMap.put(target, new ViewAccessTargetStatistics(target, tmp.getCount() + statistic.getCount(), tmp.getTimeTotal() + statistic.getTimeTotal()));
    }
    return new ArrayList<>(resultMap.values());
  }
}
