package com.leisuretimedock.blasttravelreborn.mixin;

import com.leisuretimedock.blasttravelreborn.content.entity.CannonEntity;
import com.leisuretimedock.blasttravelreborn.util.PlayerEntityDuck;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.model.PlayerModel;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
import net.minecraft.util.Mth;
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;

@Mixin(PlayerRenderer.class)
public abstract class PlayerEntityRendererMixin extends LivingEntityRenderer<AbstractClientPlayer, PlayerModel<AbstractClientPlayer>> {
	public PlayerEntityRendererMixin(EntityRendererProvider.Context context, PlayerModel<AbstractClientPlayer> entityModel, float f) {
		super(context, entityModel, f);
	}

	@Inject(method = "render*", at = @At("HEAD"), cancellable = true)
	private void blasttravel$makePlayersInCannonsInvisible(AbstractClientPlayer player, float f, float g, PoseStack matrixStack, MultiBufferSource vertexConsumerProvider, int i, CallbackInfo ci) {
		if (player.getVehicle() instanceof CannonEntity) {
			ci.cancel();
		}
	}

	@Inject(method = "setupRotations(Lnet/minecraft/client/player/AbstractClientPlayer;Lcom/mojang/blaze3d/vertex/PoseStack;FFF)V", at = @At("HEAD"), cancellable = true)
	private void blasttravel$modifyPlayerAngles(AbstractClientPlayer player, PoseStack matrices, float f, float g, float tickDelta, CallbackInfo ci) {
		if (player instanceof PlayerEntityDuck duck && duck.blasttravel$inCannonFlight()) {
			var vel = duck.blasttravel$getVelocityLerped(tickDelta);
			double horizontal = Math.sqrt(vel.x * vel.x + vel.z * vel.z);
			super.setupRotations(player, matrices, f, 270 + ((float) Math.atan2(vel.z, vel.x) * Mth.RAD_TO_DEG), tickDelta);
			matrices.mulPose(Axis.XP.rotation((Mth.PI * 1.5f) + (float) Math.atan2(vel.y, horizontal)));

			ci.cancel();
		}
	}
}
