package wtf.opal.event.listener;

import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import wtf.opal.event.EventCancellable;
import wtf.opal.event.subscriber.IEventSubscriber;

@Environment(EnvType.CLIENT)
public final class ListenerMethod {
   private final int priority;
   private final CallSite callSite;
   private final IEventSubscriber subscriber;
   private final MethodHandle dynamicInvoker;

   public ListenerMethod(int priority, CallSite callSite, IEventSubscriber subscriber) {
      this.priority = -priority;
      this.callSite = callSite;
      this.subscriber = subscriber;
      this.dynamicInvoker = callSite.dynamicInvoker();
   }

   public CallSite getCallSite() {
      return this.callSite;
   }

   public int getPriority() {
      return this.priority;
   }

   public boolean invoke(Object event) {
      if (this.subscriber.isHandlingEvents()) {
         try {
            this.dynamicInvoker.invoke((Object)this.subscriber, (Object)event);
         } catch (Throwable var3) {
            var3.printStackTrace();
            throw new RuntimeException("Error invoking event", var3);
         }

         if (event instanceof EventCancellable var2 && var2.isCancelled()) {
            return true;
         }

         return false;
      } else {
         return false;
      }
   }
}
