package com.leisuretimedock.blasttravelreborn.network.toServer;

import com.leisuretimedock.blasttravelreborn.content.entity.CannonEntity;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public record RequestFirePayload(int cannonId) {
    public RequestFirePayload(CannonEntity cannonEntity) {
        this(cannonEntity.getId());
    }

    public void write(FriendlyByteBuf buf) {
        buf.writeInt(cannonId);
    }
    public static RequestFirePayload read(FriendlyByteBuf buf) {
        return new RequestFirePayload(buf.readInt());
    }
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        if (context.getNetworkManager().getPacketListener() instanceof ServerGamePacketListenerImpl) {
            context.enqueueWork(() -> {
                ServerPlayer sender = context.getSender();
                assert sender != null;
                Entity entity = sender.level().getEntity(cannonId);
                if (entity instanceof CannonEntity cannonEntity) {
                    cannonEntity.fireServer();
                }
            });
            context.setPacketHandled(true);
        }
    }
}
