package wtf.opal.client.binding;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.ibm.icu.impl.Pair;
import java.util.Optional;
import java.util.Map.Entry;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import wtf.opal.client.Constants;
import wtf.opal.client.binding.type.InputType;

@Environment(EnvType.CLIENT)
public final class BindingService {
   private final Multimap<Pair<Integer, InputType>, IBindable> bindingMap = HashMultimap.create();

   public void register(int code, IBindable bindable, InputType inputType) {
      this.bindingMap.put(Pair.of(code, inputType), bindable);
   }

   public void clearBindings(IBindable bindable) {
      this.bindingMap.entries().removeIf(entry -> entry.getValue() == bindable);
   }

   public void dispatch(int code, InputType inputType) {
      if (Constants.mc.currentScreen == null) {
         this.bindingMap.get(Pair.of(code, inputType)).forEach(IBindable::onBindingInteraction);
      }
   }

   public Multimap<Pair<Integer, InputType>, IBindable> getBindingMap() {
      return this.bindingMap;
   }

   public Optional<Pair<Integer, InputType>> getKeyFromBindable(IBindable bindable) {
      return this.bindingMap.entries().stream().filter(entry -> ((IBindable)entry.getValue()).equals(bindable)).map(Entry::getKey).findFirst();
   }
}
