package com.leisuretimedock.blasttravelreborn.network.toServer;

import com.leisuretimedock.blasttravelreborn.network.BTRNetwork;
import com.leisuretimedock.blasttravelreborn.network.toClient.StopCannonFlightClientPayload;
import com.leisuretimedock.blasttravelreborn.util.PlayerEntityDuck;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public record StopCannonFlightServerPayload(boolean thud) {
    public StopCannonFlightServerPayload(FriendlyByteBuf buf) {
        this(buf.readBoolean());
    }
    public void write(FriendlyByteBuf buf) {
        buf.writeBoolean(thud);
    }
    public static StopCannonFlightServerPayload read(FriendlyByteBuf buf) {
        return new StopCannonFlightServerPayload(buf);
    }
    public void handler(Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        if(context.getNetworkManager().getPacketListener() instanceof ServerGamePacketListenerImpl) {
            context.enqueueWork(() -> {
                ServerPlayer sender = context.getSender();
                assert sender != null;
                ((PlayerEntityDuck) sender).blasttravel$setCannonFlight(false);
                if (sender.level() instanceof ServerLevel serverLevel) {
                    serverLevel.players().forEach(player -> BTRNetwork.CHANNEL.sendTo(new StopCannonFlightClientPayload(sender), player.connection.connection, NetworkDirection.PLAY_TO_CLIENT));
                }
                if (thud) {
                    sender.level().playSound(
                        null ,sender.getX(), sender.getY(), sender.getZ(),
                        SoundEvents.GENERIC_SMALL_FALL, SoundSource.PLAYERS, 1, 0.78f
                    );
                }
            });
            context.setPacketHandled(true);
        }
    }
}
