package com.thebrokenrail.herobrine.mixin;

import com.thebrokenrail.herobrine.HerobrineRewoven;
import com.thebrokenrail.herobrine.config.HardcodedConfig;
import com.thebrokenrail.herobrine.entity.HerobrineEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Hand;
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;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

@Mixin(PlayerEntity.class)
public class MixinPlayerEntity {
    @Inject(at = @At("HEAD"), method = "isInvulnerableTo", cancellable = true)
    public void isInvulnerableTo(DamageSource damageSource, CallbackInfoReturnable<Boolean> info) {
        PlayerEntity player = (PlayerEntity) (Object) this;
        if (damageSource == DamageSource.OUT_OF_WORLD && player.isHolding(HerobrineRewoven.BLACK_DIAMOND_ITEM)) {
            info.setReturnValue(true);
        }
    }

    @Inject(at = @At("RETURN"), method = "tick")
    public void tick(CallbackInfo info) {
        PlayerEntity player = (PlayerEntity) (Object) this;
        if (player.isAlive() && !player.getEntityWorld().isClient() && player.isHolding(HerobrineRewoven.BLACK_DIAMOND_ITEM) && player.getY() <= HardcodedConfig.HEROBRINE_PARTICLE_Y) {
            ((ServerWorld) player.getEntityWorld()).spawnParticles(ParticleTypes.DRAGON_BREATH, player.getX(), player.getY() - 0.5d, player.getZ(),  64, 0.4d, 0.4d, 0.4d, 0d);
            if (player.getY() <= HardcodedConfig.HEROBRINE_SPAWN_Y) {
                HerobrineEntity.summon(player);
                boolean isMainHand = player.getStackInHand(Hand.MAIN_HAND).getItem() == HerobrineRewoven.BLACK_DIAMOND_ITEM;
                player.setStackInHand(isMainHand ? Hand.MAIN_HAND : Hand.OFF_HAND, ItemStack.EMPTY);
                player.getEntityWorld().playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.BLOCK_END_PORTAL_SPAWN, SoundCategory.PLAYERS, 1.0f, 1.0f);
            }
        }
    }
}
