/*
 * (c) 2021 Pluto Inc.
 */
package tv.pluto.mongo.utils.episodes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import tv.pluto.mongo.entities.episodes.AgeRange;
import tv.pluto.mongo.entities.episodes.Episodes;
import tv.pluto.mongo.utils.MongoUtils;

public class AgeRangeUtils extends MongoUtils {

  public AgeRangeUtils() {
    this.genericCollection = this.collectionAgeRanges;
  }

  public Map<String, AgeRange> getAgeRangeMapForEpisodes(List<Episodes> episodesList) {
    Set<String> uniqueAgeRangeIds = new HashSet<>();
    Map<String, AgeRange> result = new HashMap<>();

    episodesList.forEach(
        episode ->
            episode.getAgeRange().forEach(ageRange -> uniqueAgeRangeIds.add(ageRange.toString())));

    String[] projection = {"countryCode", "name", "displayName", "min", "max"};

    List<AgeRange> ageRangeList = getDocumentsByIds(new ArrayList<>(uniqueAgeRangeIds), projection);

    if (!ageRangeList.isEmpty()) {
      uniqueAgeRangeIds.forEach(
          id -> {
            result.put(
                id,
                ageRangeList.stream()
                    .filter(ageRange -> ageRange.getId().equals(id))
                    .findFirst()
                    .orElse(new AgeRange()));
          });
    }

    return result;
  }
}
