package eu.mhsl.minenet.minigames.shared.inventory;

import net.kyori.adventure.text.Component;
import net.minestom.server.entity.Player;
import net.minestom.server.inventory.Inventory;
import net.minestom.server.inventory.InventoryType;
import net.minestom.server.inventory.click.ClickType;
import net.minestom.server.inventory.condition.InventoryConditionResult;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull;

import java.util.function.Consumer;

public class InteractableInventory extends Inventory {
    /**
     * Defines an Inventory with direct callbacks for ItemSlots
     * @param inventoryType
     * @param title
     */
    protected InteractableInventory(@NotNull InventoryType inventoryType, @NotNull Component title) {
        super(inventoryType, title);

        addInventoryCondition(this::onClick);
    }

    /**
     * Set Item with Callback
     * @param item
     * @param slot
     * @param callback
     */
    protected void setClickableItem(ItemStack item, int slot, Consumer<ItemClick> callback, boolean closeAfter) {
        setItemStack(slot, item);
        addInventoryCondition((player, clickedSlot, clickType, inventoryConditionResult) -> {
            if(clickedSlot == slot) {
                if(closeAfter) player.closeInventory();
                callback.accept(new ItemClick(player, this, clickedSlot, item, clickType));
            }
            inventoryConditionResult.setCancel(true);
        });
    }

    protected void setClickableItem(ItemStack item, int slot, Consumer<ItemClick> callback) {
        this.setClickableItem(item, slot, callback, false);
    }

    /**
     * Set Item without handler
     * @param item
     * @param slot
     */
    protected void setDummyItem(ItemStack item, int slot) {
        this.setClickableItem(
                item,
                slot,
                itemClick -> {}
        );
    }

    protected void setDummyItem(Material material, int slot) {
        this.setDummyItem(
                ItemStack.builder(material).customName(Component.text("")).build(),
                slot
        );
    }

    /**
     * You may want to Override this method to get more generic click events
     * @param player
     * @param slot
     * @param clickType
     * @param inventoryConditionResult
     */
    protected void onClick(Player player, int slot, ClickType clickType, InventoryConditionResult inventoryConditionResult) {

    }
}
