/*
 * Original project: RedEnvelope by KaguyaStudio-MC
 * Original project link: https://github.com/KaguyaStudio-MC/RedEnvelope
 * Modified by: LeisureTimeDock
 * This file is part of RedEnvelope
 * Licensed under Camellia License Version 1.0
 */

package top.leisuretimedock.redenvelope.core.network;

import java.util.UUID;
import java.util.function.Supplier;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
import top.leisuretimedock.redenvelope.core.util.REUtil;

public record OpenRedEnvelopePacket(UUID uuid) {

    // 编码
    public static void encode(OpenRedEnvelopePacket msg, FriendlyByteBuf buffer) {
        buffer.writeUUID(msg.uuid);
    }

    // 解码
    public static OpenRedEnvelopePacket decode(FriendlyByteBuf buffer) {
        return new OpenRedEnvelopePacket(buffer.readUUID());
    }

    // 处理
    public static void handle(OpenRedEnvelopePacket msg, Supplier<NetworkEvent.Context> ctxSupplier) {
        NetworkEvent.Context ctx = ctxSupplier.get();
        ctx.enqueueWork(() -> {
            // 确保在服务端执行
            ServerPlayer player = ctx.getSender();
            if (player != null) {
                REUtil.open(player, msg.uuid);
            }
        });
        ctx.setPacketHandled(true);
    }
    public static void _handleServer(OpenRedEnvelopePacket message, ServerPlayer serverPlayer) {
        REUtil.open(serverPlayer,message.uuid());
    }
}