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> ni, final T mj, final ServerLevel zd) throws RunningOnDifferentThreadException {
        PacketUtils.<T>ensureRunningOnSameThread(ni, mj, zd.getServer());
    }
    
    public static <T extends PacketListener> void ensureRunningOnSameThread(final Packet<T> ni, final T mj, final BlockableEventLoop<?> amn) throws RunningOnDifferentThreadException {
        if (!amn.isSameThread()) {
            amn.execute(() -> {
                if (mj.getConnection().isConnected()) {
                    ni.handle(mj);
                }
                else {
                    PacketUtils.LOGGER.debug("Ignoring packet due to disconnection: " + ni);
                }
                return;
            });
            throw RunningOnDifferentThreadException.RUNNING_ON_DIFFERENT_THREAD;
        }
    }
    
    static {
        LOGGER = LogManager.getLogger();
    }
}
