let $BlockContainerJS = Java.loadClass("dev.latvian.mods.kubejs.level.BlockContainerJS")

let musicTriggerCDs = {}

PlayerEvents.tick(event => {
    let nowTime = Date.now()
    let player = event.player
    let pData = player.persistentData
    let pName = player.name.string
    let pUuid = player.uuid.toString()
    let count = 0

    // 取CD时间（内存，不写入玩家数据）
    let triggerCD = musicTriggerCDs[pUuid] || 0
    if (nowTime - triggerCD < 5000) return

    let check = false
    // 方块监听触发器
    let bAABB = player.boundingBox.inflate(5, 4, 5)
    let blocks = BlockPos.betweenClosedStream(bAABB).map(pos => new $BlockContainerJS(player.level, pos))
    blocks.forEach(block => {
        if (check) return
        
        // 酒馆内
        if (block.id === "minecolonies:blockhuttavern") {
            // 立即标记为已触发，防止多次触发
            check = true
            // 记录当前位置，用于延迟检查
            let pos = player.position()
            player.server.scheduleInTicks(100, () => {
                // 检查100刻钟后玩家是否还在相同位置附近
                if (player.position().distanceToSqr(pos) < 100) {
                    // 再次检查附近是否有酒馆方块
                    let currentBlocks = BlockPos.betweenClosedStream(bAABB).map(p => new $BlockContainerJS(player.level, p))
                    let hasTavern = false
                    currentBlocks.forEach(b => {
                        if (b.id === "minecolonies:blockhuttavern") {
                            hasTavern = true
                        }
                    })
                    if (hasTavern) {
                        player.server.runCommandSilent(`execute as ${pName} run mt trigger tavern`)
                        musicTriggerCDs[pUuid] = Date.now() // 只写内存
                    }
                }
            })
        }
        // 许愿泉附近
        if (block.id === "wishing_fountain:wishing_fountain" && !check) {
            // 立即标记为已触发，防止多次触发
            check = true
            // 记录当前位置，用于延迟检查
            let pos = player.position()
            player.server.scheduleInTicks(100, () => {
                // 检查100刻钟后玩家是否还在相同位置附近
                if (player.position().distanceToSqr(pos) < 100) {
                    // 再次检查附近是否有许愿泉方块
                    let currentBlocks = BlockPos.betweenClosedStream(bAABB).map(p => new $BlockContainerJS(player.level, p))
                    let hasFountain = false
                    currentBlocks.forEach(b => {
                        if (b.id === "wishing_fountain:wishing_fountain") {
                            hasFountain = true
                        }
                    })
                    if (hasFountain) {
                        player.server.runCommandSilent(`execute as ${pName} run mt trigger wishing`)
                        musicTriggerCDs[pUuid] = Date.now()
                    }
                }
            })
        }
    })
    if (check) return
    // 实体监听触发器
    let pAABB = player.boundingBox.inflate(60, 30, 60)
    player.level.getEntitiesWithin(pAABB).forEach(entity => {
        if (check) return
        // 城市内
        if (
            entity.type === 'minecolonies:citizen' ||
            entity.type === 'minecolonies:visitor' ||
            entity.tags.contains('snk_swordsmen_barracks') ||
            entity.tags.contains('snk_archer_barracks') ||
            entity.tags.contains('snk_musketeer_barracks') ||
            entity.tags.contains('snk_priests_barracks') ||
            entity.tags.contains('snk_arsenal')
        ) {
            if (pData.getInt("music") === 1) {
                event.server.runCommandSilent(`execute as ${pName} run mt trigger village`)
                musicTriggerCDs[pUuid] = Date.now()
                check = true
            }
            if (pData.getInt("music") === 2 && !check) {
                event.server.runCommandSilent(`execute as ${pName} run mt trigger town`)
                musicTriggerCDs[pUuid] = Date.now()
                check = true
            }
            if (pData.getInt("music") === 3 && !check) {
                event.server.runCommandSilent(`execute as ${pName} run mt trigger metropolis`)
                musicTriggerCDs[pUuid] = Date.now()
                check = true
            }
            if (pData.getInt("music") === 4 && !check) {
                event.server.runCommandSilent(`execute as ${pName} run mt trigger pastoralism`)
                musicTriggerCDs[pUuid] = Date.now()
                check = true
            }
        }
        // 村庄内
        if (entity.type === 'minecraft:villager' && !check) {
            count = count + 1
            if (count >= 3) {
                event.server.runCommandSilent(`execute as ${pName} run mt trigger village`)
                musicTriggerCDs[pUuid] = Date.now()
                check = true
            }
        }
    })
})

FTBQuestsEvents.customReward(event => {
    if (event.reward.tags.contains('cb_townhall_1') || event.reward.tags.contains('music_1')) {
        let pData = event.player.persistentData
        pData.putInt("music", 1)
    }
    if (event.reward.tags.contains('cb_townhall_2') || event.reward.tags.contains('music_2')) {
        let pData = event.player.persistentData
        pData.putInt("music", 2)
    }
    if (event.reward.tags.contains('cb_townhall_4') || event.reward.tags.contains('music_3')) {
        let pData = event.player.persistentData
        pData.putInt("music", 3)
    }
    if (event.reward.tags.contains('music_4')) {
        let pData = event.player.persistentData
        pData.putInt("music", 4)
    }
})