package top.leisuretimedock.dglabgame.core.network.toServer;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
import org.jetbrains.annotations.NotNull;
import top.leisuretimedock.dglabgame.config.CommonConfig;

import java.util.function.Supplier;

public record UpdateStrengthConfigPacket(int maxA, int minA, int maxB, int minB) {
    public void encode(FriendlyByteBuf buf) {
        buf.writeVarInt(maxA);
        buf.writeVarInt(minA);
        buf.writeVarInt(maxB);
        buf.writeVarInt(minB);
    }

    public static UpdateStrengthConfigPacket decode(FriendlyByteBuf buf) {
        return new UpdateStrengthConfigPacket(buf.readVarInt(), buf.readVarInt(), buf.readVarInt(), buf.readVarInt());
    }

    public void handle(@NotNull Supplier<NetworkEvent.Context> contextSupplier) {
        NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            ServerPlayer sender = context.getSender();
            if (sender != null) {
                CommonConfig.MAX_STRENGTH_A.set(maxA);
                CommonConfig.MIN_STRENGTH_A.set(minA);
                CommonConfig.MAX_STRENGTH_B.set(maxB);
                CommonConfig.MIN_STRENGTH_B.set(minB);
                CommonConfig.SPEC.save();
            }
            context.setPacketHandled(true);
        });
    }
}
