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

import { teleportSkill } from "../mobs/the_snatching";
import { dimensions } from "../mobs/the_snatching";

// 监听实体受伤事件
world.afterEvents.entityHurt.subscribe((event) => {
    try {
        const { damage, damageSource, hurtEntity } = event;

        if (!damageSource || !damageSource.damagingEntity || !damageSource.damagingEntity.isValid() || !hurtEntity.isValid()) {
            return;
        }

        const damagingEntity = damageSource.damagingEntity

        if (hurtEntity.typeId !== "minecraft:player") {
            return;
        }

        const playerEquipmentComponent = hurtEntity.getComponent('minecraft:equippable');
        const playerHeadEquipment = playerEquipmentComponent.getEquipment('Head');

        if (playerHeadEquipment && playerHeadEquipment.typeId === 'pm_mock:mask_of_eyes') {
            // console.warn(`传送`);
            
            damagingEntity.dimension.spawnParticle('pm_mock:the_snatching_tp_1', damagingEntity.location);
            // hurtEntity.dimension.spawnParticle('pm_mock:the_snatching_tp_1', hurtEntity.location);
            damagingEntity.runCommand(`playsound mob.endermen.portal @a ~~~`);

            teleportSkill(damagingEntity);
        }
    } catch (error) {
        // console.error(`Error in entityHurt event: ${error.message}`);
    }
});

// 全局定时器
system.runInterval(() => {
    dimensions.forEach(dim => {
        const dimensionObj = world.getDimension(dim);
        if (dimensionObj) {
            const playerList = dimensionObj.getPlayers();
            playerList.forEach(player => {
                try {
                    const playerEquipmentComponent = player.getComponent('minecraft:equippable');
                    const playerHeadEquipment = playerEquipmentComponent.getEquipment('Head');
                    if (playerHeadEquipment && playerHeadEquipment.typeId === 'pm_mock:mask_of_eyes') {
                        player.addEffect("night_vision", 250, { showParticles: false });
                    };
                } catch (error) {
                    // console.error(`Error in global timer: ${error.message}`);
                }
            });
        }
    });
}, 2);