import { world, system } from '@minecraft/server';
import { CUSTOM_BREAK_HANDLERS, LOOKAT_HANDLERS } from '../recipes/registries.js';
import { damageEntityHeldItem } from '../utils/utils.js';
import { MinecraftBlockTypes } from '../minecraft_vanilla_data.js';

world.beforeEvents.playerBreakBlock.subscribe((event) => {
    const item = event.itemStack;
    const block = event.block;
    const entity = event.player;
    if (!block || !item) {
        return;
    }
    for (const custombreakhandler of CUSTOM_BREAK_HANDLERS) {
        if (!custombreakhandler.isValidItem(item)) {
            continue;
        }
        if (!custombreakhandler.isValidBlock(block)) {
            continue;
        }
        event.cancel = true;
        system.run(() => {
            custombreakhandler.spawnLoot(block);
            const number = custombreakhandler.damageItem(item, block);
            if (number) {
                damageEntityHeldItem(entity, number);
            }
            event.block.setType(MinecraftBlockTypes.Air);
        });
        break;
    }
});
system.runInterval(() => {
    world.getAllPlayers().forEach((player) => {
        const blockFromRayElement = player.dimension.getBlockFromRay(player.getHeadLocation(), player.getViewDirection(), {
            maxDistance: 5
        });
        if (blockFromRayElement) {
            for (let lookathandler of LOOKAT_HANDLERS) {
                if (lookathandler.isValid(player, blockFromRayElement.block)) {
                    lookathandler.onLookat(player, blockFromRayElement.block);
                    return;
                }
            }
        }
    });
}, 5);
