package net.halbear.aotg.utility;

import net.halbear.aotg.AgeoftheGods;
import net.halbear.aotg.registries.ModItems;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.DecoratedPotBlockEntity;
import net.minecraft.world.level.material.Fluids;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.capabilities.Capabilities;
import net.neoforged.neoforge.event.level.BlockEvent;
import net.neoforged.neoforge.transfer.ResourceHandler;
import net.neoforged.neoforge.transfer.item.ItemResource;

@EventBusSubscriber(modid = AgeoftheGods.MODID)
public class ServerModEventHandler {
    @SubscribeEvent
    public static void OnAlloyPotDestroy(BlockEvent.BreakEvent event){
        if (!(event.getLevel() instanceof Level level)) return;
        if (level.isClientSide()) return;

        BlockPos pos = event.getPos();
        BlockEntity blockEntity = level.getBlockEntity(pos);
        AgeoftheGods.LOGGER.debug("Block Entity Broken: " + (blockEntity == null ? "no block entity" : blockEntity.getNameForReporting()));
        if (blockEntity instanceof DecoratedPotBlockEntity potEntity) {
            AgeoftheGods.LOGGER.debug("Pot Entity Broken! ");
            ResourceHandler<ItemResource> itemHandler = level.getCapability(Capabilities.Item.BLOCK, potEntity.getBlockPos(),potEntity.getBlockState(),potEntity,null);


            if (itemHandler != null) {
                boolean hasMarker = itemHandler.getResource(0).getItem().equals(ModItems.FLUID_INDICATOR_ITEM.asItem());
                AgeoftheGods.LOGGER.debug("Pot Entity Contents Exist! Marker: " + hasMarker +" | Item in first slot: " + itemHandler.getResource(0).getItem().toString());

                if (hasMarker) {
                    potEntity.getContainerBlockEntity().setRemoved();
                    potEntity.setChanged();
                    level.setBlock(pos, Fluids.LAVA.defaultFluidState().createLegacyBlock(), 3);

                    event.setCanceled(true);
                }
            }
        }
    }
}
