package asm.mixins;

import dev.crucifixbeta.CrucifixBeta;
import dev.crucifixbeta.api.interfaces.IMouseHook;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.Mouse;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Environment(EnvType.CLIENT)
@Mixin({Mouse.class})
public class MixinMouse implements IMouseHook {
   @Shadow
   private boolean cursorLocked;
   @Final
   @Shadow
   private MinecraftClient client;
   @Shadow
   private double x;
   @Shadow
   private double y;

   @Inject(
      method = {"onMouseButton"},
      at = {@At("HEAD")}
   )
   private void onMouse(long window, int button, int action, int mods, CallbackInfo ci) {
      int var7 = -(button + 2);
      if (action == 1) {
         CrucifixBeta.MODULE.onKeyPressed(var7);
      }

      if (action == 0) {
         CrucifixBeta.MODULE.onKeyReleased(var7);
      }
   }

   @Override
   public void frogClient$lock() {
      if (this.client.isWindowFocused() && !this.cursorLocked) {
         if (!MinecraftClient.IS_SYSTEM_MAC) {
            KeyBinding.updatePressedStates();
         }

         this.cursorLocked = true;
         this.x = (double)this.client.getWindow().getWidth() / 2.0;
         this.y = (double)this.client.getWindow().getHeight() / 2.0;
         InputUtil.setCursorParameters(this.client.getWindow().getHandle(), 212995, this.x, this.y);
      }
   }
}
