import { world, system, ItemStack } from '@minecraft/server';
import { damageEntityHeldItem, calculateItemDamageAmount } from '../../utils/utils.js';
import { HammerRecipes } from '../../recipes/recipes.js';
import { MinecraftBlockTypes, MinecraftEntityTypes } from '../../minecraft_vanilla_data.js';
import { getEntityHeldItem } from '../../utils/players.js';

world.beforeEvents.playerBreakBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block;
    const item = event.itemStack;
    if (!item) {
        return;
    }
    const toolTier = HammerRecipes.HAMMER_TO_TIER.get(item.typeId);
    if (toolTier === undefined) {
        return;
    }
    for (const recipe of HammerRecipes.RECIPES) {
        if (block.typeId === recipe.blockId && toolTier >= recipe.toolTier) {
            system.runTimeout(() => {
                if (recipe.customBreakLogic) {
                    const blockCenter = block.center();
                    player.dimension.setBlockType(block.location, MinecraftBlockTypes.Air);
                    player.dimension.spawnParticle(recipe.particle, blockCenter);
                    player.dimension.playSound(recipe.sound, blockCenter);
                    system.runTimeout(() => {
                        player.dimension.spawnItem(new ItemStack(recipe.itemDrop), blockCenter);
                    }, 1);
                }
                damageEntityHeldItem(player, calculateItemDamageAmount(event.itemStack), item);
            }, 0);
            if (recipe.customBreakLogic) {
                event.cancel = true;
            }
            break;
        }
    }
});
world.afterEvents.entityHitBlock.subscribe((event) => {
    const entity = event.damagingEntity;
    const block = event.hitBlock;
    const item = getEntityHeldItem(entity);
    if (!item) {
        return;
    }
    const toolTier = HammerRecipes.HAMMER_TO_TIER.get(item.typeId);
    if (toolTier === undefined) {
        return;
    }
    for (const recipe of HammerRecipes.RECIPES) {
        if (block.typeId === recipe.blockId) {
            if (toolTier < recipe.toolTier) {
                if (entity.typeId === MinecraftEntityTypes.Player) {
                    const player = entity;
                    player.onScreenDisplay.setActionBar({
                        translate: "ftb_sieves.hammer.too_weak",
                    });
                }
            }
        }
    }
});
