package com.leisuretimedock.blasttravelreborn.network.toClient;

import com.leisuretimedock.blasttravelreborn.util.PlayerEntityDuck;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public record StopCannonFlightClientPayload(int flyingId) {
    public StopCannonFlightClientPayload(Player flying) {
        this(flying.getId());
    }
    public void write(FriendlyByteBuf buf) {
        buf.writeInt(flyingId);
    }
    public static StopCannonFlightClientPayload read (FriendlyByteBuf buf) {
        return new StopCannonFlightClientPayload(buf.readInt());
    }
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        if (context.getNetworkManager().getPacketListener() instanceof ClientPacketListener packetListener) {
            Entity entity = packetListener.getLevel().getEntity(flyingId);
            if (entity instanceof PlayerEntityDuck playerEntityDuck && entity != Minecraft.getInstance().player) {
                playerEntityDuck.blasttravel$setCannonFlight(false);
            }
            context.setPacketHandled(true);
        }
    }
}
