package dev.micle.loginprotection.network.server;

import dev.micle.loginprotection.data.ProtectedPlayer;
import dev.micle.loginprotection.network.NetworkManager;
import dev.micle.loginprotection.proxy.Proxy;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class PlayerStatePacket {
    private final ProtectedPlayer.State state;

    public PlayerStatePacket(ProtectedPlayer.State state) {
        this.state = state;
    }

    public static void encode(final PlayerStatePacket packet, final FriendlyByteBuf buffer) {
        NetworkManager.writeVersionInfo(buffer, true);
        buffer.writeUtf(packet.state.toString());
    }

    public static PlayerStatePacket decode(final FriendlyByteBuf buffer) {
        NetworkManager.checkVersion(buffer);
        return new PlayerStatePacket(ProtectedPlayer.State.valueOf(buffer.readUtf()));
    }

    public static void handle(final PlayerStatePacket packet, final Supplier<NetworkEvent.Context> contextSupplier) {
        final NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            Proxy.Client.setPlayerState(packet.state);
        });
        context.setPacketHandled(true);
    }
}
