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 dev.micle.loginprotection.proxy.Proxy;
import dev.micle.loginprotection.setup.Config;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class LastInputTickPacket {
    private final int lastInputTick;

    public LastInputTickPacket() {
        this(Proxy.Client.getLastInputTick());
    }
    public LastInputTickPacket(int lastInputTick) {
        this.lastInputTick = lastInputTick;
    }

    public static void encode(final LastInputTickPacket packet, final FriendlyByteBuf buffer) {
        NetworkManager.writeVersionInfo(buffer, false);
        buffer.writeInt(packet.lastInputTick);
    }

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

    public static void handle(final LastInputTickPacket 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;
            }

            // Check if player is afk
            if (sender.tickCount - packet.lastInputTick >= Config.Server.AFK_TIME_THRESHOLD.get() * 20) {
                ProtectedPlayerManager.updateState(sender.getUUID()); // Update state
            } else {
                ProtectedPlayerManager.startAfkTimer(sender.getUUID(), (long) ((Config.Server.AFK_TIME_THRESHOLD.get() -
                                        ((sender.tickCount - packet.lastInputTick) / 20.0)) * 1000)); // Start new afk timer
            }
        });
        context.setPacketHandled(true);
    }
}
