// priority: 5
let $BlockContainerJS = Java.loadClass("dev.latvian.mods.kubejs.level.BlockContainerJS")

// 姓名生成函数
function generateRandomName(gender) {
    let randomLastName = familyName[Math.floor(Math.random() * familyName.length)]
    let randomFirstName

    if (gender === "male") {
        randomFirstName = maleName[Math.floor(Math.random() * maleName.length)]
    } else {
        randomFirstName = femaleName[Math.floor(Math.random() * femaleName.length)]
    }

    if (familyNameFront) {
        return `${randomLastName}${randomFirstName}`
    } else {
        return `${randomFirstName} ${randomLastName}`
    }
}

PlayerEvents.loggedIn(event => {
    let player = event.player
    let pName = player.name.string
    let pUUID = player.nbt.UUID
    let pData = player.persistentData
    if (!player.tags.contains('task_1')) {
        player.setMainHandItem(Item.of(`minecraft:iron_sword`))
        player.setHeadArmorItem(Item.of(`immersive_armors:robe_helmet`,
            `{Enchantments:[{id:"l2complements:eternal",lvl:1s}],Trim:{material:"illagerinvasion:platinum",pattern:"minecraft:wayfinder"},display:{Name:
                '{"text":"领主兜帽","italic":"italic"}',
            color:3951699},"quark:RuneColor":"blank"}`))
        player.setChestArmorItem(Item.of(`immersive_armors:robe_chestplate`,
            `{Enchantments:[{id:"l2complements:eternal",lvl:1s}],Trim:{material:"illagerinvasion:platinum",pattern:"minecraft:wayfinder"},display:{Name:
                '{"text":"领主长袍","italic":"italic"}',
            color:3951699},"quark:RuneColor":"blank"}`))
        player.setLegsArmorItem(Item.of(`immersive_armors:robe_leggings`,
            `{Enchantments:[{id:"l2complements:eternal",lvl:1s}],Trim:{material:"illagerinvasion:platinum",pattern:"minecraft:wayfinder"},display:{Name:
                '{"text":"领主护腿","italic":"italic"}',
                color:3951699},"quark:RuneColor":"blank"}`))
        player.setFeetArmorItem(Item.of(`immersive_armors:robe_boots`,
            `{Enchantments:[{id:"l2complements:eternal",lvl:1s}],Trim:{material:"illagerinvasion:platinum",pattern:"minecraft:wayfinder"},display:{Name:
                '{"text":"领主靴子","italic":"italic"}',
                color:3951699},"quark:RuneColor":"blank"}`))
        player.inventory.setItem(9, Item.of(`minecraft:bread`, 64))
        player.inventory.setItem(10, Item.of(`minecraft:amethyst_shard`, 140))
        player.inventory.setItem(11, Item.of(`minecolonies:supplycampdeployer`, 1))
        player.addTag('task_1')
        if (!pData.getInt("MaxScale")) {
            pData.putInt("MaxScale", pioneer * 3)
            player.tell(`远征军上限初始化完成,初始为${pioneer * 3}，上限为${scaleLimit}`)
        }
        event.server.scheduleInTicks(120, () => {
            event.server.runCommandSilent(`team join white ${pName}`)
            let task_1 = () => {
                if (!player.player || !player.isPlayer()) return
                let Soldier = 0
                // 获取区域内的方块位置
                let AABB = player.boundingBox.inflate(10, 5, 10)
                let blocks = BlockPos.betweenClosedStream(AABB).map(pos => new $BlockContainerJS(event.level, pos))
                blocks.forEach(block => {
                    if (Soldier >= pioneer) return
                    if (block.id !== "minecraft:air") return
                    let pos = block.pos
                    //检查下方
                    let blockDown = new $BlockContainerJS(event.level, BlockPos(pos.x, pos.y - 1, pos.z))
                    if (blockDown.id === "minecraft:air") return
                    //检查上方
                    let blockUp = new $BlockContainerJS(event.level, BlockPos(pos.x, pos.y + 1, pos.z))
                    if (blockUp.id !== "minecraft:air") return
                    //检查通过，开召
                    let newSoldier = event.level.createEntity("hundred_years_war:shieldman")
                    newSoldier.setPosition(pos.x, pos.y, pos.z)

                    // 生成随机性别和名字
                    let gender = Math.random() < 0.5 ? "male" : "female"
                    let fullName = generateRandomName(gender)
                    let displayName = `[卫兵]${fullName}`

                    /////////////数据库/////////////
                    let newData = newSoldier.persistentData

                    // 士兵数据库
                    let sSoldierData = newData.getCompound("soldier")
                    sSoldierData.putString("Owner", player.uuid.toString())
                    sSoldierData.putInt("HomePosX", Math.floor(pos.x))
                    sSoldierData.putInt("HomePosY", Math.floor(pos.y))
                    sSoldierData.putInt("HomePosZ", Math.floor(pos.z))
                    sSoldierData.putString("HomePosDim", player.level.dimension.path)
                    sSoldierData.putInt("Occupation", 3)
                    sSoldierData.putString("Type", "shieldman")
                    sSoldierData.putString("Gender", gender)
                    sSoldierData.putString("FullName", fullName)
                    sSoldierData.putString("Profession", "shieldman")
                    sSoldierData.putString("ProfessionDisplay", "卫兵")
                    newData.put("soldier", sSoldierData)

                    // 坐骑数据库
                    let rideData = newData.getCompound("ride")
                    rideData.putBoolean("replace", true)
                    rideData.putString("rideID", "hundred_years_war:mounted_lancer_rider")
                    let ChargeWeaponData = rideData.getCompound("ChargeWeapon")
                    ChargeWeaponData.putBoolean("Count", true)
                    ChargeWeaponData.putString("id", "hundred_years_war:iron_lance")
                    rideData.put("ChargeWeapon", ChargeWeaponData)
                    newData.put("ride", rideData)

                    // 命令数据库
                    let commandData = newData.getCompound("command")
                    commandData.putInt("Behavior", 1) // 警戒模式
                    commandData.putInt("PosX", Math.floor(pos.x))
                    commandData.putInt("PosY", Math.floor(pos.y))
                    commandData.putInt("PosZ", Math.floor(pos.z))
                    newData.put("command", commandData)

                    // 玩家数据库
                    let pSoldierData = pData.getCompound("soldier")
                    let newUuid = newSoldier.uuid.toString()
                    let newUuidData = pSoldierData.getCompound(newUuid)
                    newUuidData.putString("uuid", newUuid)
                    newUuidData.putInt("Behavior", 1)
                    pSoldierData.put(newUuid, newUuidData)
                    pData.put("soldier", pSoldierData)
                    //////////////////////////

                    newSoldier.spawn()
                    newData.putString("pUuid", player.uuid.toString())
                    newData.putString("type", "shieldman")
                    newData.putString("team", "white")

                    // 设置士兵基本属性和装备
                    newSoldier.mergeNbt(`{
                        OwnerUUID:${pUUID},
                        CustomName:'{"text":"${displayName}"}',
                        ArmorItems:[
                            {Count:1b,id:"minecraft:leather_boots"},
                            {Count:1b,id:"minecraft:leather_leggings"},
                            {Count:1b,id:"minecraft:leather_chestplate"},
                            {Count:1b,id:"minecraft:leather_helmet"}
                        ],
                        HandItems:[
                            {Count:1b,id:"minecraft:stone_sword"},
                            {Count:1b,id:"shieldexex:wooden_tower_shield"}
                        ]
                    }`)

                    // 使用新的属性系统
                    global.AttributeEnhancement(newSoldier, "minecraft:generic.max_health", "cb_initial_health", 30, 0)
                    global.AttributeEnhancement(newSoldier, "obscure_api:dodge", "cb_initial_dodge", 0.3, 1)

                    newSoldier.setHealth(9999)

                    // 使用行为翻译系统设置警戒行为
                    event.server.scheduleInTicks(5, () => {
                        event.server.runCommandSilent(`team join white ${newSoldier.uuid.toString()}`)
                        global.BehaviorTranslation(newSoldier, player)
                    })

                    Soldier++
                })
                if (Soldier < pioneer) {
                    //没有找到能放兵的位置，3秒后重新检查
                    event.server.scheduleInTicks(60, task_1)
                } else {
                    player.tell(`近卫：领主大人，先锋部队已经集结完毕`)
                    event.server.scheduleInTicks(60, () => {
                        event.server.runCommandSilent(`title ${pName} title "按住R选择编入远征军，即可对近卫下达命令"`)
                        player.tell(`在小地图上寻找你的士兵头像`)
                        player.tell(`按住R选择编入远征军`)
                    })
                    player.addTag('task_2')
                }
            }
            task_1()
        })
    }
})

ItemEvents.foodEaten(event => {
    if (event.player) {
        let player = event.player
        if (!player.tags.contains('task_3')) {
            player.addTag('task_3')
        }
    }
})

FTBQuestsEvents.customReward(event => {
    let server = event.server
    let player = event.player
    let pData = player.persistentData
    let pUuid = player.uuid.toString()
    let pName = player.name.string
    let pAABB = player.boundingBox.inflate(100, 50, 100)
    if (event.reward.tags.contains('bd_transfer_2') && !player.tags.contains('task_4')) {
        let confirm = true
        player.level.getEntitiesWithin(pAABB).forEach(oldTransfer => {
            if (oldTransfer.type === "minecraft:armor_stand" && oldTransfer.tags.contains('snk_transfer')) {
                confirm = false
                return
            }
        })
        if (confirm === false) {
            player.tell('§c检测到100米矩形范围内存在其他传送点，无法在这么近的距离建设新的传送点')
            return
        }
        let confirm2 = false
        player.level.getEntitiesWithin(pAABB).forEach(citizen => {
            if (confirm2) return
            if (citizen.type.toString() === 'minecolonies:citizen' && citizen.nbt.ForgeData.owner === pUuid) {
                confirm2 = true
            }
        })
        if (confirm2 === false) {
            player.tell('§c仅能在殖民地内放置赠送石碑')
            return
        }
        server.runCommandSilent(`execute at ${pName} run place template snk:transfer ~-1 ~-4 ~-1`)
        player.teleportTo(player.level.dimension.path, player.x + 1, player.y, player.z, player.yaw, player.pitch)
        player.server.scheduleInTicks(5, () => {
            let pAABB2 = player.boundingBox.inflate(3, 6, 3)
            player.level.getEntitiesWithin(pAABB2).forEach(transfer => {
                if (transfer.tags.contains('snk_transfer') && !transfer.persistentData.contains("pUuid")) {
                    transfer.persistentData.putString("pUuid", pUuid)
                    let team = player.team.name
                    let tUuid = transfer.uuid.toString()
                    player.server.runCommandSilent(`execute as ${tUuid} run team join ${team} @s`)
                    transfer.persistentData.putString(`team`, `${team}`)
                    player.tell('赠送传送点已建立，请下蹲右键传送石碑给石碑取名')
                    player.addTag('task_4')
                }
            })
        })
    }
    if (event.reward.tags.contains('bd_transfer_2') && player.tags.contains('task_4')) {
        player.tell('§c你已经放置过赠送石碑！')
    }
    //自动攀爬开关
    if (event.reward.tags.contains('task_sha')) {
        if (!pData.contains('task_sha') || pData.getInt('task_sha') == 0) {
            pData.putInt('task_sha', 1)
            player.setAttributeBaseValue("forge:step_height_addition", 1)
            player.tell("自动攀爬已开启")
        } else {
            pData.putInt('task_sha', 0)
            player.setAttributeBaseValue("forge:step_height_addition", 0)
            player.tell("自动攀爬已关闭")
        }
    }
})