package net.halbear.aotg.utility.Networking;

import net.halbear.aotg.AgeoftheGods;
import net.halbear.aotg.custom.blocks.AlloyFurnace.AlloyFurnaceBlockEntity;
import net.halbear.aotg.custom.blocks.AlloyFurnace.AlloyFurnaceUpdateHandler;
import net.halbear.aotg.registries.ModBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;

import static net.halbear.aotg.custom.blocks.AlloyFurnace.AlloyFurnaceMultiBlock.MODEL_PART;
import static net.halbear.aotg.custom.blocks.AlloyFurnace.AlloyFurnaceMultiBlock.PARENT_BLOCK;

@EventBusSubscriber
public record AlloyFurnaceGuiButtonHandler(int buttonID, int x, int y, int z) implements CustomPacketPayload {
    public static final Type<AlloyFurnaceGuiButtonHandler> TYPE = new Type<>(Identifier.fromNamespaceAndPath(AgeoftheGods.MODID, "alloy_furnace_buttons"));
    public static final StreamCodec<RegistryFriendlyByteBuf, AlloyFurnaceGuiButtonHandler> STREAM_CODEC = StreamCodec.of((RegistryFriendlyByteBuf buffer, AlloyFurnaceGuiButtonHandler message) -> {
        buffer.writeInt(message.buttonID);
        buffer.writeInt(message.x);
        buffer.writeInt(message.y);
        buffer.writeInt(message.z);
    }, (RegistryFriendlyByteBuf buffer) -> new AlloyFurnaceGuiButtonHandler(buffer.readInt(), buffer.readInt(), buffer.readInt(), buffer.readInt()));

    @Override
    public Type<AlloyFurnaceGuiButtonHandler> type() {
        return TYPE;
    }

    public static void handleData(final AlloyFurnaceGuiButtonHandler message, final IPayloadContext context) {
        if (context.flow() == PacketFlow.SERVERBOUND) {
            context.enqueueWork(() -> handleButtonAction(context.player(), message.buttonID, message.x, message.y, message.z)).exceptionally(e -> {
                context.connection().disconnect(Component.literal(e.getMessage()));
                return null;
            });
        }
    }

    public static void handleButtonAction(Player entity, int buttonID, int x, int y, int z) {
        Level world = entity.level();
        AgeoftheGods.LOGGER.debug("BUTTON PRESSED, Entity: " + entity.getName().getString() + " | ButtonID: " + buttonID + " | XYZ: " + x + " " + y + " " + z);
        if (!world.getChunkSource().hasChunk(SectionPos.blockToSectionCoord(x), SectionPos.blockToSectionCoord(z)))
            return;
        if (buttonID == 0) {
            BlockPos TargetPos = new BlockPos(x,y,z);
            BlockState blockstate = world.getBlockState(new BlockPos(x,y,z));
            if(blockstate.getBlock().getName().getString().equals(ModBlocks.ALLOY_FURNACE.get().getName().getString()) && !blockstate.getValue(PARENT_BLOCK)) {
                int ModelPart = blockstate.getValue(MODEL_PART);
                TargetPos = AlloyFurnaceUpdateHandler.GetParentPosFromModelPart(world, ModelPart, blockstate, new BlockPos(x, y, z));
            }
            BlockEntity blockEntity = world.getBlockEntity(new BlockPos(TargetPos));
            if(blockEntity instanceof AlloyFurnaceBlockEntity alloyFurnaceBlockEntity){
                alloyFurnaceBlockEntity.PushBellow();
            }
        }
    }
    @SubscribeEvent
    public static void registerMessage(final RegisterPayloadHandlersEvent event) {
        final PayloadRegistrar registrar = event.registrar("1.0.0");

        registrar.playToServer(
                AlloyFurnaceGuiButtonHandler.TYPE,
                AlloyFurnaceGuiButtonHandler.STREAM_CODEC,
                AlloyFurnaceGuiButtonHandler::handleData
        );
    }
    @SubscribeEvent
    public static void registerMessage(FMLCommonSetupEvent event) {
        AgeoftheGods.addNetworkMessage(AlloyFurnaceGuiButtonHandler.TYPE, AlloyFurnaceGuiButtonHandler.STREAM_CODEC, AlloyFurnaceGuiButtonHandler::handleData);
    }

}
