// priority: 5

//tag记录：
//讲台
//剑士营地      snk_swordsmen_barracks   附属盔甲架：snk_swordsmen_mark
//射手营地      snk_archer_barracks      附属盔甲架：snk_archer_mark
//火枪营地      snk_musketeer_barracks   附属盔甲架：snk_musketeer_mark
//祭司营地      snk_priests_barracks     附属盔甲架：snk_priests_mark
//军械库        snk_arsenal              附属盔甲架：snk_arsenal_mark

//制箭台
//火炮防御塔    snk_artillery_defense
//射手防御塔    snk_archer_defense

//钟
//广场         snk_squares
//马厩         snk_stable

//函数：寻找雕纹石砖并记录
let $BlockContainerJS = Java.loadClass("dev.latvian.mods.kubejs.level.BlockContainerJS")
function blockCoordinates(mark) {
    let mData = mark.persistentData
    let xzExtend = mData.contains("xzExtend") ? mData.getInt("xzExtend") : 2
    let upExtend = mData.contains("upExtend") ? mData.getInt("upExtend") : 6
    let downExtend = mData.contains("downExtend") ? mData.getInt("downExtend") : 1
    let sAABB = mark.boundingBox.expandTowards(xzExtend, upExtend, xzExtend).expandTowards(-xzExtend, -downExtend, -xzExtend)
    let blocks = BlockPos.betweenClosedStream(sAABB).map(pos => new $BlockContainerJS(mark.level, pos))
    let check = false
    blocks.forEach(block => {
        if (check) return
        if (block.id === "minecraft:chiseled_stone_bricks") {
            mData.putIntArray("soldier_pos", [block.pos.x, block.pos.y, block.pos.z])
            check = true
        }
    })
}

BlockEvents.rightClicked(event => {
    let player = event.player
    let pName = player.name.string
    let pUuid = player.uuid.toString()
    let pUUID = player.nbt.UUID
    let pData = player.persistentData
    // 访问讲台触发
    if (event.block.id === 'minecraft:lectern') {
        let CAPABILITY_ID = CAPABILITY.map(config => config.prefix)
        let AABB = player.boundingBox.expandTowards(4, 1, 4).expandTowards(-4, -4, -4)
        player.level.getEntitiesWithin(AABB).forEach(building => {
            if (!(
                building.tags.contains('snk_swordsmen_barracks') ||
                building.tags.contains('snk_archer_barracks') ||
                building.tags.contains('snk_musketeer_barracks') ||
                building.tags.contains('snk_priests_barracks') ||
                building.tags.contains('snk_arsenal')
            )) return
            let bData = building.persistentData
            let contrastUuid = bData.getString("pUuid")
            let xzExtend = bData.contains("xzExtend") ? bData.getInt("xzExtend") : 8
            let upExtend = bData.contains("upExtend") ? bData.getInt("upExtend") : 8
            let downExtend = bData.contains("downExtend") ? bData.getInt("downExtend") : 1
            let bAABB = building.boundingBox.expandTowards(xzExtend, upExtend, xzExtend).expandTowards(-xzExtend, -downExtend, -xzExtend)
            //剑士营地
            if (building.tags.contains('snk_swordsmen_barracks')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属剑士营地，已登记`)
                        //FTB任务标记
                        if (!player.tags.contains('task_5')) { player.addTag('task_5') }
                    }
                    //将盔甲架重命名为剑士营地
                    if (!building.customName) {
                        building.setCustomName("剑士营地")
                    }
                    //打开任务页面
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 20FF9EAF2E96564C`)
                    building.level.getEntitiesWithin(bAABB).forEach(mark => {
                        let mData = mark.persistentData
                        if (!mData.contains("soldier_pos")) {
                            blockCoordinates(mark)
                        }
                        //复制属性标签和等级
                        CAPABILITY_ID.forEach(config => {
                            if (player.persistentData.getInt(config)) {
                                if (mark.tags.contains('snk_swordsmen_mark') && mData.getInt(config) != pData.getInt(config)) {
                                    mData.putInt(config, pData.getInt(config))
                                }
                            }
                        })
                    })
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个剑士营地不属于你`)
                }
            }
            //射手营地
            if (building.tags.contains('snk_archer_barracks')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属射手营地，已登记`)
                    }
                    //将盔甲架重命名为射手营地
                    if (!building.customName) {
                        building.setCustomName("射手营地")
                    }
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 2DFCFB92BC4E9A26`)
                    building.level.getEntitiesWithin(bAABB).forEach(mark => {
                        let mData = mark.persistentData
                        if (!mData.contains("soldier_pos")) {
                            blockCoordinates(mark)
                        }
                        //复制属性标签和等级
                        CAPABILITY_ID.forEach(config => {
                            if (player.persistentData.getInt(config)) {
                                if (mark.tags.contains('snk_archer_mark') && mData.getInt(config) != pData.getInt(config)) {
                                    mData.putInt(config, pData.getInt(config))
                                }
                            }
                        })
                    })
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个射手营地不属于你`)
                }
            }
            //火枪营地
            if (building.tags.contains('snk_musketeer_barracks')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属火枪营地，已登记`)
                    }
                    //将盔甲架重命名为火枪营地
                    if (!building.customName) {
                        building.setCustomName("火枪营地")
                    }
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 555051B8B8940A6B`)
                    building.level.getEntitiesWithin(bAABB).forEach(mark => {
                        let mData = mark.persistentData
                        if (!mData.contains("soldier_pos")) {
                            blockCoordinates(mark)
                        }
                        //复制属性标签和等级
                        CAPABILITY_ID.forEach(config => {
                            if (player.persistentData.getInt(config)) {
                                if (mark.tags.contains('snk_musketeer_mark') && mData.getInt(config) != pData.getInt(config)) {
                                    mData.putInt(config, pData.getInt(config))
                                }
                            }
                        })
                    })
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个火枪营地不属于你`)
                }
            }
            //祭司营地
            if (building.tags.contains('snk_priests_barracks')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属祭司营地，已登记`)
                    }
                    //将盔甲架重命名为祭司营地
                    if (!building.customName) {
                        building.setCustomName("祭司营地")
                    }
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 3A67E49C3D1999D8`)
                    building.level.getEntitiesWithin(bAABB).forEach(mark => {
                        let mData = mark.persistentData
                        if (!mData.contains("soldier_pos")) {
                            blockCoordinates(mark)
                        }
                        //复制属性标签和等级
                        CAPABILITY_ID.forEach(config => {
                            if (player.persistentData.getInt(config)) {
                                if (mark.tags.contains('snk_priests_mark') && mData.getInt(config) != pData.getInt(config)) {
                                    mData.putInt(config, pData.getInt(config))
                                }
                            }
                        })
                    })
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个祭司营地不属于你`)
                }
            }
            //军械库
            if (building.tags.contains('snk_arsenal')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属军械库，已登记`)
                    }
                    //将盔甲架重命名为军械库
                    if (!building.customName) {
                        building.setCustomName("军械库")
                    }
                    //修理等级
                    if (player.persistentData.getInt("cb_ar")) {
                        building.level.getEntitiesWithin(bAABB).forEach(mark => {
                            let mData = mark.persistentData
                            if (mark.tags.contains('snk_arsenal_mark') && mData.getInt("cb_ar") != pData.getInt("cb_ar")) {
                                mData.putInt("cb_ar", pData.getInt("cb_ar"))
                                player.tell(`自动修理已启用，等级${pData.getInt("cb_ar")})`)
                            }
                        })
                    }
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个军械库不属于你`)
                }
            }
        })
    }
    // 访问制箭台触发
    if (event.block.id === 'minecraft:fletching_table') {
        let AABB = player.boundingBox.expandTowards(3, 1, 3).expandTowards(-3, -4, -3)
        player.level.getEntitiesWithin(AABB).forEach(building => {
            if (!(
                building.tags.contains('snk_artillery_defense') ||
                building.tags.contains('snk_archer_defense')
            )) return
            let bData = building.persistentData
            let contrastUuid = bData.getString("pUuid")
            if (!bData.contains("TD_pos")) {
                let xzExtend = bData.contains("xzExtend") ? bData.getInt("xzExtend") : 2
                let upExtend = bData.contains("upExtend") ? bData.getInt("upExtend") : 20
                let downExtend = bData.contains("downExtend") ? bData.getInt("downExtend") : 4
                let bAABB = building.boundingBox.expandTowards(xzExtend, upExtend, xzExtend).expandTowards(-xzExtend, -downExtend, -xzExtend)
                let blocks = BlockPos.betweenClosedStream(bAABB).map(pos => new $BlockContainerJS(building.level, pos))
                blocks.forEach(block => {
                    if (block.id === "minecraft:chiseled_stone_bricks") {
                        bData.putIntArray("TD_pos", [block.pos.x, block.pos.y, block.pos.z])
                        return
                    }
                })
            }
            if (building.tags.contains('snk_artillery_defense')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属炮塔，已登记`)
                    }
                    //将盔甲架重命名为炮塔
                    if (!building.customName) {
                        building.setCustomName("炮塔")
                    }
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 35449F4D20347EB6`)
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个炮塔不属于你`)
                }
            }
            if (building.tags.contains('snk_archer_defense')) {
                if (!bData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!bData.contains("pUuid")) {
                        bData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属防御塔，已登记`)
                    }
                    //将盔甲架重命名为防御塔
                    if (!building.customName) {
                        building.setCustomName("防御塔")
                    }
                    event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 1BBD82009D269A6C`)
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个防御塔不属于你`)
                }
            }
        })
    }
    // 访问钟触发
    if (event.block.id === 'minecraft:bell') {
        let AABB = player.boundingBox.expandTowards(6, 1, 6).expandTowards(-6, -4, -6)
        player.level.getEntitiesWithin(AABB).forEach(building => {
            if (!(
                building.tags.contains('snk_stable') ||
                building.tags.contains('snk_squares')
            )) return
            if (building.tags.contains('snk_stable')) {
                let sData = building.persistentData
                let contrastUuid = sData.getString("pUuid")
                if (!sData.contains("pUuid") || contrastUuid === pUuid) {
                    if (!sData.contains("pUuid")) {
                        sData.putString("pUuid", pUuid)
                        player.tell(`检测到无所属马厩，已登记`)
                    }
                    //将盔甲架重命名为马厩
                    if (!building.customName) {
                        building.setCustomName("马厩")
                    }
                    event.server.entities.forEach(oldmount => {
                        if (!(oldmount.tags.contains('snk_mount') && oldmount.nbt.Owner && pUUID.equals(oldmount.nbt.Owner))) return
                        oldmount.removeTag("snk_mount")
                        player.tell(`§c检测到已存在其他登记坐骑，旧坐骑已注销登记`)
                    })
                    let sAABB = building.boundingBox.inflate(12, 4, 12)
                    let allow = true
                    building.level.getEntitiesWithin(sAABB).forEach(mount => {
                        if (allow === false) return
                        if (mount.nbt.Tame === 1 && mount.nbt.Owner && pUUID.equals(mount.nbt.Owner)) {
                            mount.addTag("snk_mount")
                            player.tell(`在附近检测到已驯服生物，已登记`)
                            player.stopRiding()
                            mount.teleportTo(building.level.dimension.path, building.x, building.y + 3, building.z, 0, 0)
                            allow = false
                        }
                    })
                }
                if (contrastUuid && contrastUuid != pUuid) {
                    player.tell(`§c这个马厩不属于你`)
                }
            }
            if (building.tags.contains('snk_squares')) {
                pData.putString("SPDim", building.level.dimension.path)
                pData.putInt("SP_X", building.x)
                pData.putInt("SP_Y", building.y + 3)
                pData.putInt("SP_Z", building.z)
                player.tell(`集结广场已登记`)
            }
        })
    }
    //访问愿泉显示鸣谢名单
    if (event.block.id === 'wishing_fountain:wishing_fountain') {
        if (player.shiftKeyDown) {
            event.server.runCommandSilent(`execute as ${pName} run ftbquests open_book 43790C6FBDC59771`)
        }
    }
})

//方块破坏事件
//禁止破坏传送石碑
BlockEvents.broken('waystones:waystone', event => {
    let player = event.player
    if (player.gameMode.isSurvival()) {
        player.tell('请在快速建造页面重置传送点')
        player.tell('村庄传送点不可拆除')
        event.cancel()
    }
})