package wtf.opal.client.binding.repository;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.lwjgl.glfw.GLFW;
import wtf.opal.client.binding.BindingService;
import wtf.opal.client.binding.type.InputType;
import wtf.opal.event.EventDispatcher;
import wtf.opal.event.impl.press.KeyPressEvent;
import wtf.opal.event.impl.press.MousePressEvent;
import wtf.opal.event.subscriber.IEventSubscriber;
import wtf.opal.event.subscriber.Subscribe;

@Environment(EnvType.CLIENT)
public final class BindRepository implements IEventSubscriber {
   private final BindingService bindingService = new BindingService();
   private final Map<String, Integer> namedBindingMap = new HashMap<>();
   public static final String GLFW_KEY_PREFIX;

   public BindRepository() {
      try {
         for (Field var4 : GLFW.class.getDeclaredFields()) {
            if (var4.getName().startsWith("GLFW_KEY_")) {
               this.namedBindingMap.put(var4.getName().substring(("GLFW_KEY_").length()), var4.getInt(null));
            }
         }

         for (int var6 = 0; var6 < 10; var6++) {
            this.namedBindingMap.put("MOUSE_" + var6, var6);
         }

         this.namedBindingMap.put("CLEAR", -1);
      } catch (IllegalAccessException var5) {
         var5.printStackTrace();
      }

      EventDispatcher.subscribe(this);
   }

   public Map<String, Integer> getNamedBindingMap() {
      return this.namedBindingMap;
   }

   public String getNameFromInteger(int bind) {
      return this.namedBindingMap.entrySet().stream().filter(entry -> entry.getValue() == bind).map(Entry::getKey).findFirst().orElse(null);
   }

   public BindingService getBindingService() {
      return this.bindingService;
   }

   @Subscribe
   public void onKeyPress(KeyPressEvent event) {
      this.bindingService.dispatch(event.getInteractionCode(), InputType.KEYBOARD);
   }

   @Subscribe
   public void onMousePress(MousePressEvent event) {
      this.bindingService.dispatch(event.getInteractionCode(), InputType.MOUSE);
   }

   static {

      GLFW_KEY_PREFIX = "GLFW_KEY_";
   }
}
