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 UpdateServerConfigPacket(int serverPort, int maxConnections) {
    public void encode(FriendlyByteBuf buf) {
        buf.writeVarInt(serverPort);
        buf.writeVarInt(maxConnections);
    }

    public static UpdateServerConfigPacket decode(FriendlyByteBuf buf) {
        return new UpdateServerConfigPacket(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 && sender.hasPermissions(4)) {
                CommonConfig.SERVER_PORT.set(serverPort);
                CommonConfig.MAX_CONNECTIONS.set(maxConnections);
                CommonConfig.SPEC.save();
            }
            context.setPacketHandled(true);
        });
    }
}
