/*
 * 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 net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.NotNull;
import top.leisuretimedock.redenvelope.core.capability.RECapability;
import top.leisuretimedock.redenvelope.core.capability.RedEnvelopeStorage;

import java.util.function.Supplier;

public record SyncREStoragePacket(CompoundTag data) {

    public static @NotNull SyncREStoragePacket decode(@NotNull FriendlyByteBuf buffer) {
        return new SyncREStoragePacket(buffer.readNbt());
    }

    public static void encode(@NotNull SyncREStoragePacket storage, @NotNull FriendlyByteBuf buffer) {
        buffer.writeNbt(storage.data);
    }


    public static void handle(SyncREStoragePacket message, @NotNull Supplier<NetworkEvent.Context> contextSupplier) {
        NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(getRunnable(message));
        context.setPacketHandled(true);
    }

    @OnlyIn(Dist.CLIENT)
    private static @NotNull Runnable getRunnable(SyncREStoragePacket message) {
        return () -> {
            LocalPlayer player = Minecraft.getInstance().player;
            if (player != null) {
                player.getCapability(RECapability.HONGBAO_STORAGE).ifPresent(storage -> {
                    storage.deserializeNBT(message.data);
                });
            }
        };
    }
}
