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

// 停滞药水效果，持续判断是不是快速移动了
function stasisEffect(entity) {
    let entityLocation = entity.location;

    function checkMovement() {
        try {
            if (!entity.isValid()) {
                return;
            }

            // 读取动态属性中的持续时间
            let remainingTicks = entity.getDynamicProperty('pm_mock:stasis_effect_ticks');
            if (remainingTicks === undefined || remainingTicks < 0) {
                return;
            }

            let newLocation = entity.location;
            const distance = Math.sqrt(
                Math.pow(newLocation.x - entityLocation.x, 2) +
                Math.pow(newLocation.y - entityLocation.y, 2) +
                Math.pow(newLocation.z - entityLocation.z, 2)
            );

            if (distance > 5.0) {
                // console.warn(`entity ${entity.name} is moving too fast!`);
                entity.teleport(entityLocation, { checkForBlocks: true });
            } else {
                entityLocation = newLocation;
                entity.dimension.spawnParticle('pm_mock:stasis_potion_1', entityLocation);
            }

            // 清除周围的末影珍珠
            try {
                entity.dimension.getEntities({
                    location: entityLocation,
                    maxDistance: 10,
                    type: "minecraft:ender_pearl",
                }).forEach(pearlEntity => {
                    if (pearlEntity.getComponent('minecraft:projectile').owner === entity) {
                        // console.warn(`Removing ender pearl from ${entity.name}`);
                        pearlEntity.remove();
                    }
                })
                
            } catch (error) {
                
            }
            
            // 显示
            showRemainingTime(entity);

            // 减少剩余时间
            entity.setDynamicProperty('pm_mock:stasis_effect_ticks', remainingTicks - 1);



            system.runTimeout(checkMovement, 1);
        } catch (error) {
            // console.error(`Error in stasisEffect for entity ${entity.name}:`, error);
        }
    }

    checkMovement();
}

// 监听事件
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceEntity } = event;

    // 应用停滞药水事件
    if (id === 'pm_mock:stasis_potion') {
        const duration = message.duration || 200; // 从消息中获取持续时间，默认为200
        applyStasisEffect(sourceEntity, duration);
    }

    // 药水碰撞在地上事件
    else if (id === 'pm_mock:stasis_potion_hit') {
        sourceEntity.dimension.spawnParticle('pm_mock:stasis_potion_3', sourceEntity.location);
        sourceEntity.dimension.playSound('random.glass', sourceEntity.location);

        const entityList = sourceEntity.dimension.getEntities({
            location: sourceEntity.location,
            maxDistance: 4,
            excludeTypes: ["minecraft:item", "minecraft:xp_orb", "minecraft:arrow", "minecraft:thrown_trident", "minecraft:snowball", "minecraft:ender_pearl"],
        });
        for (const entity of entityList) {
            if (entity.isValid()) {
                const duration = message.duration || 200; // 从消息中获取持续时间，默认为200
                applyStasisEffect(entity, duration);
            }
        }
    }
});

// 辅助函数：应用停滞效果
function applyStasisEffect(entity, duration) {
    let remainingTicks = entity.getDynamicProperty('pm_mock:stasis_effect_ticks');
    if (remainingTicks === undefined || remainingTicks <= 0) {
        entity.setDynamicProperty('pm_mock:stasis_effect_ticks', duration);
        stasisEffect(entity);
    } else if (duration > remainingTicks) {
        // 如果新的持续时间大于当前持续时间，则重置持续时间为新的持续时间
        entity.setDynamicProperty('pm_mock:stasis_effect_ticks', duration);
    }
    showRemainingTime(entity);
}

// 提示玩家当前剩余时间
function showRemainingTime(entity) {
    let remainingTicks = entity.getDynamicProperty('pm_mock:stasis_effect_ticks');
    if (remainingTicks !== undefined && remainingTicks >= 0) {
        const remainingSeconds = Math.ceil(remainingTicks / 20);
        entity.runCommand(`title @s actionbar Oh no! You have §eStasis!§r\nYou can't throw ender pearls in §c${remainingSeconds}s§r`)
    }
}


// 监听玩家使用物品完成
world.afterEvents.itemCompleteUse.subscribe((event) => {
    const { source: player, itemStack } = event;

    // console.warn(`player ${player.name} used item ${itemStack.typeId} 222`);

    if (itemStack.typeId === 'minecraft:milk_bucket') {
        player.setDynamicProperty('pm_mock:stasis_effect_ticks', 0);
    }
})