package asm.mixins;

import dev.crucifixbeta.mod.features.SpearPort;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.HeldItemFeatureRenderer;
import net.minecraft.client.render.model.json.ModelTransformationMode;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Arm;
import org.spongepowered.asm.mixin.Mixin;
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({HeldItemFeatureRenderer.class})
public abstract class MixinHeldItemFeatureRenderer {
   @Inject(
      method = {"renderItem"},
      at = {@At("HEAD")}
   )
   private void crucifix$beginThirdPersonSpearRender(
      LivingEntity entity,
      ItemStack stack,
      ModelTransformationMode transformationMode,
      Arm arm,
      MatrixStack matrices,
      VertexConsumerProvider vertexConsumers,
      int light,
      CallbackInfo ci
   ) {
      if (SpearPort.isSpear(stack) && isThirdPersonHand(transformationMode)) {
         SpearPort.setInHandRender(true);
      }
   }

   @Inject(
      method = {"renderItem"},
      at = {@At("RETURN")}
   )
   private void crucifix$endThirdPersonSpearRender(
      LivingEntity entity,
      ItemStack stack,
      ModelTransformationMode transformationMode,
      Arm arm,
      MatrixStack matrices,
      VertexConsumerProvider vertexConsumers,
      int light,
      CallbackInfo ci
   ) {
      if (SpearPort.isSpear(stack) && isThirdPersonHand(transformationMode)) {
         SpearPort.setInHandRender(false);
      }
   }

   private static boolean isThirdPersonHand(ModelTransformationMode transformationMode) {
      return transformationMode == ModelTransformationMode.THIRD_PERSON_RIGHT_HAND || transformationMode == ModelTransformationMode.THIRD_PERSON_LEFT_HAND;
   }
}
