package net.minecraft.network.protocol;

import org.apache.logging.log4j.LogManager;
import net.minecraft.server.RunningOnDifferentThreadException;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraft.network.PacketListener;
import net.minecraft.server.level.ServerLevel;
import org.apache.logging.log4j.Logger;

public class PacketUtils {
    private static final Logger LOGGER;
    
    public static <T extends PacketListener> void ensureRunningOnSameThread(final Packet<T> lt, final T ky, final ServerLevel xd) throws RunningOnDifferentThreadException {
        PacketUtils.<T>ensureRunningOnSameThread(lt, ky, xd.getServer());
    }
    
    public static <T extends PacketListener> void ensureRunningOnSameThread(final Packet<T> lt, final T ky, final BlockableEventLoop<?> ais) throws RunningOnDifferentThreadException {
        if (!ais.isSameThread()) {
            ais.execute(() -> {
                if (ky.getConnection().isConnected()) {
                    lt.handle(ky);
                }
                else {
                    PacketUtils.LOGGER.debug("Ignoring packet due to disconnection: " + lt);
                }
                return;
            });
            throw RunningOnDifferentThreadException.RUNNING_ON_DIFFERENT_THREAD;
        }
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
}
