package dev.micle.loginprotection.network.client;

import dev.micle.loginprotection.data.ProtectedPlayer;
import dev.micle.loginprotection.data.ProtectedPlayerManager;
import dev.micle.loginprotection.network.NetworkManager;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class InputPacket {
    public static void encode(final InputPacket packet, final FriendlyByteBuf buffer) {
        NetworkManager.writeVersionInfo(buffer, false);
    }

    public static InputPacket decode(final FriendlyByteBuf buffer) {
        NetworkManager.checkVersion(buffer);
        return new InputPacket();
    }

    public static void handle(final InputPacket packet, final Supplier<NetworkEvent.Context> contextSupplier) {
        final NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            // Get sender
            ServerPlayer sender = context.getSender();
            if (sender == null) {
                return;
            }

            // Get protected player
            ProtectedPlayer protectedPlayer = ProtectedPlayerManager.getPlayer(sender.getUUID());
            if (protectedPlayer == null) {
                return;
            }

            // Update player state if they are joining or afk
            if (protectedPlayer.getState().equals(ProtectedPlayer.State.JOINING) ||
                    protectedPlayer.getState().equals(ProtectedPlayer.State.AFK)) {
                ProtectedPlayerManager.updateState(protectedPlayer.getPlayerUUID());
            }
        });
        context.setPacketHandled(true);
    }
}
