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

const useEndScroll = {
    onUse(event) {

        // 处理物品数量减少
        const player = event.source;
        const playerEquipmentComponent = player.getComponent('minecraft:equippable');
        const playerMainhandItem = playerEquipmentComponent.getEquipment('Mainhand');

        if (playerMainhandItem?.typeId == "pm_mock:end_scroll") {
            const itemAmount = playerMainhandItem.amount;
            if (itemAmount > 1) {
                playerMainhandItem.amount = itemAmount - 1;
                playerEquipmentComponent.setEquipment('Mainhand', playerMainhandItem);
            } else {
                playerEquipmentComponent.setEquipment('Mainhand', null);
            }
        }


        
        //立刻获得隐身、播放粒子、获得无敌、音效
        player.addEffect("invisibility", 10, { amplifier: 1, showParticles: false });
        player.addEffect("resistance", 10, { amplifier: 10, showParticles: false });
        player.runCommand(`playsound mob.endermen.portal @a ~~~`);
        player.dimension.spawnParticle('pm_mock:the_snatching_tp_1', player.location);


        // 高频设置隐身、无敌、粒子，直到时间结束
        const skillTimeLimit = 100;
        const skillInterval = 4;

        for (let i = skillInterval; i < skillTimeLimit; i=i+skillInterval) {
            system.runTimeout(() => {
                if (player.isValid()) {
                    player.addEffect("invisibility", 10, { amplifier: 1, showParticles: false });
                    player.addEffect("resistance", 10, { amplifier: 10, showParticles: false });
                    player.dimension.spawnParticle('pm_mock:the_snatching_idle_2', player.location);

                }
                
            }, i);
        }



        // 时间结束后、取消隐身、无敌、粒子、音效
        system.runTimeout(() => {
            if (player.isValid()) {
                player.removeEffect("invisibility");
                player.removeEffect("resistance");
                player.dimension.spawnParticle('pm_mock:the_snatching_tp_1', player.location);
                player.runCommand(`playsound mob.endermen.portal @a ~~~`);

            }
        }, skillTimeLimit);
    }
}



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