Add itemUpdateHandler

This commit is contained in:
NichtStudioCode 2021-03-31 13:47:35 +02:00
parent dc381dba6e
commit f0d1ac5eaf

@ -12,6 +12,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.*; import java.util.*;
import java.util.function.Consumer;
public class VirtualInventory implements ConfigurationSerializable { public class VirtualInventory implements ConfigurationSerializable {
@ -20,6 +21,7 @@ public class VirtualInventory implements ConfigurationSerializable {
private final UUID uuid; private final UUID uuid;
private int size; private int size;
private ItemStack[] items; private ItemStack[] items;
private Consumer<ItemUpdateEvent> itemUpdateHandler;
/** /**
* Creates a new {@link VirtualInventory}. * Creates a new {@link VirtualInventory}.
@ -396,7 +398,7 @@ public class VirtualInventory implements ConfigurationSerializable {
private int findFullSlot(ItemStack itemStack) { private int findFullSlot(ItemStack itemStack) {
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
ItemStack currentStack = items[i]; ItemStack currentStack = items[i];
if (currentStack != null if (currentStack != null
&& currentStack.getAmount() == currentStack.getMaxStackSize() && currentStack.getAmount() == currentStack.getMaxStackSize()
&& currentStack.isSimilar(itemStack)) return i; && currentStack.isSimilar(itemStack)) return i;
} }
@ -471,8 +473,8 @@ public class VirtualInventory implements ConfigurationSerializable {
private ItemUpdateEvent createAndCallEvent(int index, Player player, ItemStack previousItemStack, ItemStack newItemStack) { private ItemUpdateEvent createAndCallEvent(int index, Player player, ItemStack previousItemStack, ItemStack newItemStack) {
ItemUpdateEvent event = new ItemUpdateEvent(this, index, player, previousItemStack, newItemStack); ItemUpdateEvent event = new ItemUpdateEvent(this, index, player, previousItemStack, newItemStack);
if (itemUpdateHandler != null) itemUpdateHandler.accept(event);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
return event; return event;
} }
@ -485,6 +487,19 @@ public class VirtualInventory implements ConfigurationSerializable {
return uuid; return uuid;
} }
/**
* Sets the item update handler which is an alternative for using
* Bukkit's event system for handling item updates in this virtual
* inventory. The item update handler is called before the Bukkit event
* is fired and all changes made are visible when catching Bukkit's
* event.
*
* @param itemUpdateHandler The item update handler
*/
public void setItemUpdateHandler(Consumer<ItemUpdateEvent> itemUpdateHandler) {
this.itemUpdateHandler = itemUpdateHandler;
}
/** /**
* Serializes this {@link VirtualInventory} to a {@link Map} * Serializes this {@link VirtualInventory} to a {@link Map}
* *