package net.Chipperfluff.chipi.block;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import net.Chipperfluff.chipi.advancement.ModCriteria;

public class VoidBlock extends Block {

    public VoidBlock(Settings settings) {
        super(settings);
    }

    private void voidKill(World world, Entity entity) {
        if (world.isClient) return;

        if (entity instanceof ItemEntity) {
            entity.kill();
            return;
        }

        if (entity instanceof LivingEntity living) {
            if (living instanceof PlayerEntity player) {
                if (player.isCreative() || player.isSpectator()) {
                    return;
                }
            }

            boolean burning = living.isOnFire();

            Identifier damageId = burning ? new Identifier("chipi", "void_block_fire") : new Identifier("chipi", "void_block");

            RegistryEntry<DamageType> damageType = world.getRegistryManager()
                .get(RegistryKeys.DAMAGE_TYPE)
                .entryOf(RegistryKey.of(RegistryKeys.DAMAGE_TYPE, damageId));

            DamageSource source = new DamageSource(damageType);

            if (living instanceof ServerPlayerEntity serverPlayer) {
                if (burning) {
                    ModCriteria.VOID_CONSUMED_FIRE_TRIGGER.trigger(serverPlayer);
                } else {
                    ModCriteria.VOID_CONSUMED_TRIGGER.trigger(serverPlayer);
                }
            }

            living.damage(source, Float.MAX_VALUE);
        }
    }

    @Override
    public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) {
        voidKill(world, entity);
    }

    @Override
    public void onSteppedOn(World world, BlockPos pos, BlockState state, Entity entity) {
        voidKill(world, entity);
    }
}
