package com.acethewildfire.acesbs.mixin;

import com.acethewildfire.acesbs.item.ModItems;
import com.acethewildfire.acesbs.item.custom.SovsPlateCarrierArmorItem;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;

import java.util.Objects;

@Mixin(PlayerEntity.class)
public abstract class PlayerEntityMixin{

    @Shadow @Final
    PlayerInventory inventory;

    @Shadow public abstract Text getName();

    @Inject(method = "damage", at = @At(value = "TAIL"), locals = LocalCapture.CAPTURE_FAILSOFT, cancellable = true)
    private void damageMixin(ServerWorld world, DamageSource source, float amount, CallbackInfoReturnable<Boolean> cir) {
        PlayerEntity player = (PlayerEntity)(Object)this;

        ItemStack chest = player.getEquippedStack(EquipmentSlot.CHEST);
        if (!chest.isEmpty() && chest.getItem() == ModItems.BERSERKERS_PAULDRON && Objects.equals(this.getName().getLiteralString(), "Tennocraft12")){
            if (!world.isClient()) {
                world.playSound(null, player.getX(),player.getY(), player.getZ(), SoundEvents.ENTITY_SKELETON_HURT, SoundCategory.PLAYERS, 2f, 1f);
            }
            cir.setReturnValue(true);
        }

        if (chest.getItem() instanceof SovsPlateCarrierArmorItem) {

            int durabilityDamage = 1;

            chest.setDamage(Math.min(
                    chest.getDamage() + durabilityDamage,
                    chest.getMaxDamage() - 1
            ));
        }
    }

    @Inject(method = "damageArmor", at = @At("HEAD"), cancellable = true)
    private void stopVanillaArmorDamage(DamageSource source, float amount, CallbackInfo ci) {

        PlayerEntity player = (PlayerEntity)(Object)this;

        ItemStack chest = player.getEquippedStack(EquipmentSlot.CHEST);

        if (chest.getItem() instanceof SovsPlateCarrierArmorItem) {
            ci.cancel(); // prevent vanilla durability loss
        }
    }
}
