import { world, system } from "@minecraft/server";

import { handleItemDurability } from "./cavernite_pickaxe";
import { pushEntityTowardsPlayer } from "../mobs/stormspitter";

const usePole = {
    onUse(event) {
        const player = event.source;

        // 如果玩家正在骑乘stormspitter，不做任何事情
        const ridingComponent = player.getComponent("minecraft:riding");
        if (ridingComponent && ridingComponent.entityRidingOn.typeId === "pm_mock:stormspitter") {
            return;
        }

        // 处理耐久度
        handleItemDurability(player);
        // 寻找附近的属主是玩家的stormspitter
        const stormspitters = player.dimension.getEntities({
            type: "pm_mock:stormspitter",
            location: player.location,
            maxDistance: 64,
        });

        stormspitters.forEach(entity => {
            const tameComponent = entity.getComponent("minecraft:tameable");
            if (tameComponent && tameComponent.tamedToPlayer && tameComponent.tamedToPlayer === player) {
                entity.triggerEvent("hover_start");
                pushEntityTowardsPlayer(entity, player);
                system.runTimeout(() => {
                    if (player.isValid()) {
                        player.runCommand(`title @s actionbar Stormspitter is §eapproaching you§r.`);
                    }
                }, 2);
                
            }
            // console.warn(`tamedComponent: ${tameComponent}`)
        });
    }
}



world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
    itemComponentRegistry.registerCustomComponent("pm_mock:phantom_membrane_pole", usePole);
});