/*
 * Original project: RedEnvelope by KaguyaStudio-MC
 * Modified by: LeisureTimeDock
 * 仅播放给指定客户端的网络包
 */
package top.leisuretimedock.redenvelope.core.network;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.registries.ForgeRegistries;

import java.util.function.Supplier;

public record PlaySoundToClientPacket(ResourceLocation soundId, SoundSource source, float volume, float pitch, double x, double y, double z) {

    public PlaySoundToClientPacket(SoundEvent sound, SoundSource source, float volume, float pitch, double x, double y, double z) {
        this(ForgeRegistries.SOUND_EVENTS.getKey(sound), source, volume, pitch, x, y, z);
    }

    public static PlaySoundToClientPacket decode(FriendlyByteBuf buf) {
        return new PlaySoundToClientPacket(
                buf.readResourceLocation(),
                buf.readEnum(SoundSource.class),
                buf.readFloat(),
                buf.readFloat(),
                buf.readDouble(),
                buf.readDouble(),
                buf.readDouble()
        );
    }

    public static void encode(PlaySoundToClientPacket packet ,FriendlyByteBuf buf) {
        buf.writeResourceLocation(packet.soundId);
        buf.writeEnum(packet.source);
        buf.writeFloat(packet.volume);
        buf.writeFloat(packet.pitch);
        buf.writeDouble(packet.x);
        buf.writeDouble(packet.y);
        buf.writeDouble(packet.z);
    }

    public static void handle(PlaySoundToClientPacket msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            // 客户端执行
            handleClient(msg);
        });
        ctx.get().setPacketHandled(true);
    }

    @OnlyIn(Dist.CLIENT)
    private static void handleClient(PlaySoundToClientPacket msg) {
        Player player = net.minecraft.client.Minecraft.getInstance().player;
        if (player != null) {
            SoundEvent soundEvent = ForgeRegistries.SOUND_EVENTS.getValue(msg.soundId);
            if (soundEvent != null) {
                player.level().playLocalSound(
                        msg.x, msg.y, msg.z,
                        soundEvent,
                        msg.source,
                        msg.volume,
                        msg.pitch,
                        false // 是否使用距离衰减
                );
            }
        }
    }
}