package com.acethewildfire.acesbs.mixin;

import com.acethewildfire.acesbs.item.custom.SmeltingAxe;
import com.acethewildfire.acesbs.item.custom.SmeltingHammer;
import com.acethewildfire.acesbs.item.custom.SmeltingPickaxe;
import com.acethewildfire.acesbs.item.custom.SmeltingShovel;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters;
import net.minecraft.loot.context.LootWorldContext;
import net.minecraft.recipe.RecipeEntry;
import net.minecraft.recipe.RecipeType;
import net.minecraft.recipe.SmeltingRecipe;
import net.minecraft.recipe.input.SingleStackRecipeInput;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Mixin(Block.class)
public class BlockMixin {

    @Inject(
            method = "getDroppedStacks(Lnet/minecraft/block/BlockState;Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/entity/BlockEntity;Lnet/minecraft/entity/Entity;Lnet/minecraft/item/ItemStack;)Ljava/util/List;",
            at = @At("RETURN"),
            cancellable = true
    )
    private static void smeltDrops(
            BlockState state, ServerWorld world, BlockPos pos, BlockEntity blockEntity, Entity entity, ItemStack stack, CallbackInfoReturnable<List<ItemStack>> cir
    ) {
        if (!(stack.getItem() instanceof SmeltingPickaxe) && !(stack.getItem() instanceof SmeltingHammer) && !(stack.getItem() instanceof SmeltingAxe) && !(stack.getItem() instanceof SmeltingShovel)) return;

        List<ItemStack> originalDrops = cir.getReturnValue();
        List<ItemStack> newDrops = new ArrayList<>();

        for (ItemStack drop : originalDrops) {
            Optional<RecipeEntry<SmeltingRecipe>> recipe =
                    world.getRecipeManager().getFirstMatch(
                            RecipeType.SMELTING,
                            new SingleStackRecipeInput(drop),
                            world
                    );

            ItemStack result = recipe
                    .map(r -> r.value().craft(new SingleStackRecipeInput(drop), world.getRegistryManager()))
                    .orElse(drop);

            result.setCount(drop.getCount());
            newDrops.add(result);
        }

        cir.setReturnValue(newDrops);
    }
}
