package dev.crucifixbeta.api.utils.move;

import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.MathHelper;

@Environment(EnvType.CLIENT)
public class MoveUtils {
   private static final MinecraftClient mc = MinecraftClient.getInstance();

   private static float direction(float forward, float strafe) {
      float var2 = mc.player.getYaw();
      boolean var3 = forward > 0.0F;
      boolean var4 = forward < 0.0F;
      boolean var5 = strafe > 0.0F;
      boolean var6 = strafe < 0.0F;
      boolean var7 = var5 || var6;
      boolean var8 = var3 || var4;
      if (forward != 0.0F || strafe != 0.0F) {
         if (var4 && !var7) {
            return var2 + 180.0F;
         }

         if (var3 && var6) {
            return var2 + 45.0F;
         }

         if (var3 && var5) {
            return var2 - 45.0F;
         }

         if (!var8 && var6) {
            return var2 + 90.0F;
         }

         if (!var8 && var5) {
            return var2 - 90.0F;
         }

         if (var4 && var6) {
            return var2 + 135.0F;
         }

         if (var4) {
            return var2 - 135.0F;
         }
      }

      return var2;
   }

   public static void fixMovement(float yaw) {
      if (mc.player != null) {
         float var1 = mc.player.input.movementForward;
         float var2 = mc.player.input.movementSideways;
         byte var3 = 45;
         float var4 = 22.5F;
         float var5 = Math.max(Math.abs(var1), Math.abs(var2));
         double var6 = (double)MathHelper.wrapDegrees(direction(var1, var2) - yaw);
         double var8 = Math.abs(var6);
         var1 = 0.0F;
         var2 = 0.0F;
         if (var8 <= (double)((float)var3 + var4)) {
            var1++;
         } else if (var8 >= (double)(180.0F - (float)var3 - var4)) {
            var1--;
         }

         if (var6 >= (double)((float)var3 - var4) && var6 <= (double)(180.0F - (float)var3 + var4)) {
            var2--;
         } else if (var6 <= (double)((float)(-var3) + var4) && var6 >= (double)(-180.0F + (float)var3 - var4)) {
            var2++;
         }

         var1 *= var5;
         var2 *= var5;
         mc.player.input.movementForward = var1;
         mc.player.input.movementSideways = var2;
      }
   }

   public static boolean isMoving() {
      return mc.player == null
         ? false
         : mc.player.input.movementForward != 0.0F
            || mc.player.input.movementSideways != 0.0F
            || mc.options.jumpKey.isPressed()
            || mc.options.leftKey.isPressed()
            || mc.options.rightKey.isPressed()
            || mc.options.forwardKey.isPressed()
            || mc.options.backKey.isPressed();
   }
}
