package codechicken.nei.recipe.widget; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.function.Function; import net.minecraft.item.ItemStack; import codechicken.nei.FavoriteRecipes; import codechicken.nei.NEIServerUtils; public class PermutationsCycler { protected final Map> permutations; protected final Map favoriteCounts; protected final Function> loader; protected Runnable onInvalidate = null; protected int favoriteRevision = -1; public PermutationsCycler(Map> storage, Map favoriteStorage, Function> loader) { this.permutations = storage; this.favoriteCounts = favoriteStorage; this.loader = loader; } public PermutationsCycler onInvalidate(Runnable callback) { this.onInvalidate = callback; return this; } public boolean validate() { final int rev = FavoriteRecipes.getRevision(); if (this.favoriteRevision != rev) { this.favoriteRevision = rev; this.permutations.clear(); this.favoriteCounts.clear(); if (this.onInvalidate != null) { this.onInvalidate.run(); } return true; } return false; } public void invalidate() { this.favoriteRevision = -1; validate(); } public boolean contains(K key) { validate(); return this.permutations.containsKey(key); } public List get(K key) { validate(); List items = this.permutations.get(key); if (items == null) { items = new ArrayList<>(this.loader.apply(key)); items.sort(Comparator.comparing(FavoriteRecipes::containsManual).reversed()); int favoriteCount = 0; if (items.size() > 1) { for (ItemStack stack : items) { if (!FavoriteRecipes.containsManual(stack)) break; favoriteCount++; } } this.permutations.put(key, items); this.favoriteCounts.put(key, favoriteCount); } return items; } public int getFavoriteCount(K key) { get(key); return this.favoriteCounts.getOrDefault(key, 0); } public ItemStack getCycled(K key, int cycle) { final List items = get(key); final int favoriteCount = this.favoriteCounts.getOrDefault(key, 0); final int size = favoriteCount > 0 ? favoriteCount : items.size(); return size > 0 ? items.get(cycle % size) : null; } public static int indexOf(List list, ItemStack stack) { for (int i = 0; i < list.size(); i++) { if (NEIServerUtils.areStacksSameType(list.get(i), stack)) { return i; } } return -1; } // Hash key with the same equality as NEIServerUtils.areStacksSameType public static Object getStackKey(ItemStack stack) { return Arrays .asList(stack.getItem(), stack.getHasSubtypes() ? stack.getItemDamage() : 0, stack.stackTagCompound); } }