package dev.crucifixbeta.mod.modules.impl.render;

import dev.crucifixbeta.api.events.eventbus.EventListener;
import dev.crucifixbeta.api.events.impl.HeldItemRendererEvent;
import dev.crucifixbeta.api.utils.Wrapper;
import dev.crucifixbeta.mod.modules.Module;
import dev.crucifixbeta.mod.modules.settings.impl.BooleanSetting;
import dev.crucifixbeta.mod.modules.settings.impl.SliderSetting;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.item.ToolItem;
import net.minecraft.util.Hand;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RotationAxis;

@Environment(EnvType.CLIENT)
public class ItemRotation extends Module implements Wrapper {
   private final SliderSetting speed = this.add(new SliderSetting("Speed", 4.0, 0.1F, 20.0, 0.1F));
   private final SliderSetting xRotation = this.add(new SliderSetting("X-Rotation", 0.0, -180.0, 180.0, 1.0));
   private final SliderSetting yRotation = this.add(new SliderSetting("Y-Rotation", 0.0, -180.0, 180.0, 1.0));
   private final SliderSetting zRotation = this.add(new SliderSetting("Z-Rotation", 0.0, -180.0, 180.0, 1.0));
   private final BooleanSetting toolsOnly = this.add(new BooleanSetting("Tools Only", false));
   private final BooleanSetting noRotateWhenHurt = this.add(new BooleanSetting("No Hurt Rotate", true));
   private float rotationAngle = 0.0F;
   private int lastSelectedSlot = -1;

   public ItemRotation() {
      super("ItemRotation", Module.Category.Render);
      this.setChinese("\u7269\u54c1\u65cb\u8f6c");
   }

   @EventListener
   public void onHeldItemRenderer(HeldItemRendererEvent event) {
      if (event.getHand() == Hand.MAIN_HAND) {
         if (!(mc.player.getAttackCooldownProgress(0.5F) < 1.0F)) {
            if (!this.noRotateWhenHurt.getValue() || mc.player.hurtTime <= 0) {
               if (!this.toolsOnly.getValue() || mc.player.getMainHandStack().getItem() instanceof ToolItem) {
                  if (mc.player.getInventory().selectedSlot != this.lastSelectedSlot) {
                     this.rotationAngle = 0.0F;
                     this.lastSelectedSlot = mc.player.getInventory().selectedSlot;
                  }

                  this.rotationAngle = (this.rotationAngle + this.speed.getValueFloat()) % 360.0F;
                  event.getStack()
                     .multiply(RotationAxis.POSITIVE_Y.rotationDegrees(MathHelper.wrapDegrees(this.yRotation.getValueFloat() + this.rotationAngle)));
               }
            }
         }
      }
   }
}
