
package de.ivu.elect.jee.entity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

public class EagerLoadingCollector<E> {

  private final Set<EagerLoading<E>> eagerLoadings = new HashSet<>();

  public EagerLoadingCollector() {
    super();
  }

  public EagerLoadingCollector<E> add(@Nullable EagerLoading<E> eagerLoading) {
    if (eagerLoading != null) {
      eagerLoadings.add(eagerLoading);
    }

    return this;
  }

  public List<E> eagerLoad(List<E> entities) {
    if (eagerLoadings.isEmpty()) {
      return entities;
    }

    List<E> result = new ArrayList<>(entities.size());

    for (E entity : entities) {
      E eagerLoaded = entity;

      for (EagerLoading<E> eagerLoading : eagerLoadings) {
        eagerLoaded = eagerLoading.eagerLoad(eagerLoaded);
      }

      result.add(eagerLoaded);
    }

    return result;
  }

  public static <E> EagerLoadingCollector<E> create() {
    return new EagerLoadingCollector<>();
  }
}
