// 获取玩家所有跟随状态士兵的UUID列表
function getFollowingSoldierUUIDs(player) {
    let followingSoldiers = []
    let pData = player.persistentData
    let pSoldierData = pData.getCompound("soldier")
    
    // 遍历玩家所有士兵数据
    pSoldierData.getAllKeys().forEach(soldierUUID => {
        let soldierData = pSoldierData.getCompound(soldierUUID)

        // 检查士兵是否处于跟随状态 (Behavior = 2)
        if (soldierData.getInt("Behavior") === 2) {
            followingSoldiers.push(soldierUUID)
        }
    })
    
    return followingSoldiers
}

// 异步传送跟随士兵到玩家位置
function teleportFollowingSoldiers(player) {
    let followingUUIDs = getFollowingSoldierUUIDs(player)

    if (followingUUIDs.length === 0) {
        return
    }
    
    // 异步处理每个士兵，每10tick传送一个
    followingUUIDs.forEach((soldierUUID, index) => {
        let delayTicks = index * 5
        
        player.server.scheduleInTicks(delayTicks, () => {
            // 使用新的单个士兵传送函数
            global.TPSoldier(player, soldierUUID)
        })
    })
}

// 玩家传送事件
ForgeEvents.onEvent("net.minecraftforge.event.entity.EntityTeleportEvent", event => {
    if (event.entity.type === 'minecraft:player') {
        let player = event.entity
        
        // 延迟传送士兵，等待玩家传送完成和地形加载
        player.server.scheduleInTicks(20, () => {
            teleportFollowingSoldiers(player)
        })
    }
})

// 指路石传送事件
ForgeEvents.onEvent("net.blay09.mods.waystones.api.WaystoneTeleportEvent$Pre", event => {
    if (event.context.entity.type === 'minecraft:player') {
        let player = event.context.entity
        
        // 延迟传送士兵，等待玩家传送完成和地形加载
        player.server.scheduleInTicks(20, () => {
            teleportFollowingSoldiers(player)
        })

        // 手持传送石获得返程石（保留此功能）
        let mainHandItem = player.getMainHandItem()
        if (mainHandItem.id === 'waystones:warp_stone') {
            let fragile_dim = player.level.dimension.path
            let fragile_x = player.x
            let fragile_y = player.y
            let fragile_z = player.z
            let specialItem = Item.of('l2complements:fragile_warp_stone', {
                display: {
                    Name: { text: "返程石", color: "gold", italic: false },
                    Lore: [
                        { text: "返回使用传送石传送的位置" }
                    ]
                },
                pos: {
                    dim: fragile_dim,
                    x: fragile_x,
                    y: fragile_y,
                    z: fragile_z
                }
            })
            player.give(specialItem)
            player.tell(Text.gold("传送石的残余能量记录了位置"))
        }
    }
})

// 跨维度传送事件
ForgeEvents.onEvent("net.minecraftforge.event.entity.EntityTravelToDimensionEvent", event => {
    if (event.entity.type === 'minecraft:player') {
        let player = event.entity
               
        // 延迟传送士兵，等待玩家跨维度完成
        player.server.scheduleInTicks(20, () => { 
            teleportFollowingSoldiers(player)
        })
    }
})