// Native Minecraft 1.21.11
package com.xfestudio.mydimensionlord.platform;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.listener.EventListener;
import net.minecraftforge.eventbus.internal.Event;
import net.minecraftforge.eventbus.api.event.characteristic.Cancellable;

/** Dispatches protection events to their native buses and retains temporary test listeners. */
public final class PortEvents {
    private record Registration(EventBus<?> bus, EventListener listener) {}
    private static final Map<Object, Registration> LISTENERS = new IdentityHashMap<>();
    @SuppressWarnings("unchecked") private static <T extends Event> EventBus<T> bus(Class<T> type) {
        try { return (EventBus<T>)type.getField("BUS").get(null); }
        catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Missing native event bus for " + type, e); }
    }
    @SuppressWarnings("unchecked") public static <T extends Event> boolean post(T event) {
        boolean cancelled = bus((Class<T>)event.getClass()).post(event);
        return cancelled || (event instanceof net.minecraftforge.common.util.HasResult result
                && result.getResult().isDenied());
    }
    public static synchronized <T extends Event> void addListener(byte priority, boolean receiveCanceled, Class<T> type, Consumer<T> listener) {
        EventBus<T> bus = bus(type);
        LISTENERS.put(listener, new Registration(bus, bus.addListener(priority, listener)));
    }
    @SuppressWarnings("unchecked") public static synchronized <T extends Event & Cancellable> void addListener(byte priority, boolean receiveCanceled, Class<T> type, Predicate<T> listener) {
        CancellableEventBus<T> bus = (CancellableEventBus<T>)bus(type);
        LISTENERS.put(listener, new Registration(bus, bus.addListener(priority, listener)));
    }
    public static synchronized void unregister(Object listener) {
        Registration registration = LISTENERS.remove(listener);
        if (registration != null) registration.bus.removeListener(registration.listener);
    }
}
