package com.trunksbomb.minetriad.compat.jei;

import java.util.List;

import com.trunksbomb.minetriad.MineTriad;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.item.CardItem;
import com.trunksbomb.minetriad.registry.TriadDataComponents;
import com.trunksbomb.minetriad.registry.TriadItems;

import mezz.jei.api.IModPlugin;
import mezz.jei.api.JeiPlugin;
import mezz.jei.api.ingredients.subtypes.ISubtypeInterpreter;
import mezz.jei.api.registration.IExtraIngredientRegistration;
import mezz.jei.api.registration.ISubtypeRegistration;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;

@JeiPlugin
public final class MineTriadJeiPlugin implements IModPlugin {
    private static final ResourceLocation PLUGIN_UID = ResourceLocation.fromNamespaceAndPath(MineTriad.MOD_ID, "jei_plugin");
    private static final ISubtypeInterpreter<ItemStack> CARD_SUBTYPE = new ISubtypeInterpreter<>() {
        @Override
        public Object getSubtypeData(ItemStack stack, mezz.jei.api.ingredients.subtypes.UidContext context) {
            CardStackData data = stack.get(TriadDataComponents.CARD_DATA);
            return data == null || CardStackData.EMPTY.equals(data) ? null : data.cardId().toString();
        }

        @Override
        public String getLegacyStringSubtypeInfo(ItemStack stack, mezz.jei.api.ingredients.subtypes.UidContext context) {
            CardStackData data = stack.get(TriadDataComponents.CARD_DATA);
            return data == null || CardStackData.EMPTY.equals(data) ? "" : data.cardId().toString();
        }
    };

    @Override
    public ResourceLocation getPluginUid() {
        return PLUGIN_UID;
    }

    @Override
    public void registerItemSubtypes(ISubtypeRegistration registration) {
        registration.registerSubtypeInterpreter(TriadItems.TRIAD_CARD.get(), CARD_SUBTYPE);
    }

    @Override
    public void registerExtraIngredients(IExtraIngredientRegistration registration) {
        List<ItemStack> cardStacks = CardRegistry.all().stream()
                .map(card -> CardItem.createCardStack(card.id(), TriadItems.TRIAD_CARD.get()))
                .toList();
        registration.addExtraItemStacks(cardStacks);
    }
}
