package ru.dbotthepony.mc.otm.mixin;

import net.minecraft.sounds.SoundSource;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.projectile.AbstractHurtingProjectile;
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.CallbackInfoReturnable;
import ru.dbotthepony.mc.otm.capability.MatteryCapability;
import ru.dbotthepony.mc.otm.registry.MSoundEvents;

@Mixin(AbstractHurtingProjectile.class)
public class MixinAbstractHurtingProjectile {
	@Inject(
		method = "hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z",
		at = @At(
			value = "INVOKE",
			target = "Lnet/minecraft/world/entity/projectile/AbstractHurtingProjectile;markHurt()V",
			ordinal = 0
		)
	)
	public void onProjectileHit(DamageSource pSource, float pAmount, CallbackInfoReturnable<Boolean> cir) {
		Entity entity = pSource.getEntity();
		if (entity == null) return;

		entity.getCapability(MatteryCapability.MATTERY_PLAYER).ifPresent(cap -> {
			AbstractHurtingProjectile proj = (AbstractHurtingProjectile)(Object)this;

			if (cap.isAndroid() && proj.getOwner() != entity) {
				entity.level().playSound(entity, proj.blockPosition(), MSoundEvents.INSTANCE.getANDROID_PROJ_PARRY(), SoundSource.PLAYERS, 1.0f, 0.95f + entity.level().random.nextFloat() * 0.1f);
			}
		});
	}
}
