// priority: 0

//火炮防御塔    snk_artillery_defense
//射手防御塔    snk_archer_defense

//安装火炮函数
function AssembleTowerDefense(event, config) {
  let server = event.server
  let player = event.player
  let pUUID = player.nbt.UUID
  let team = player.team.name
  let AABB = player.boundingBox
    .expandTowards(6, 1, 6)
    .expandTowards(-6, -4, -6)
  player.level.getEntitiesWithin(AABB).forEach((building) => {
    let bUuid = building.uuid.toString()
    let bData = building.persistentData
    let [mx, my, mz] = bData.getIntArray("TD_pos")
    if (!(building.tags.contains("snk_artillery_defense") || building.tags.contains("snk_archer_defense"))) return

    let costs = [
      { id: config.costItem, count: config.costAmount },
      { id: config.costItem2, count: config.costAmount2 },
    ];
    if (!global.ConsumableItems(player, costs)) return

    if (building.tags.contains("snk_artillery_defense")) {
      let check = true
      server.entities.forEach((defense) => {
        if (
          defense.tags.contains("snk_td_registered") &&
          bUuid === defense.persistentData.getString("mUuid")
        ) {
          if (defense.type.toString() === config.entityId) {
            check = false
            defense.teleportTo(building.level.dimension.path, mx + 0.5, my + 2, mz + 0.5, 0, 0);
          } else {
            player.tell(`§c检测到已有不相同的攻城器械,旧器械已拆解`)
            defense.mergeNbt(`{Health:0,DeathTime:19}`)
          }
        }
      });
      if (check === false) {
        player.tell(`§c检测到已有相同的攻城器械，取消组装`)
        return
      }
      let newTD = event.level.createEntity(config.entityId)
      let newData = newTD.persistentData
      newTD.setPosition(mx + 0.5, my + 1, mz + 0.5)
      newTD.spawn()
      newData.putString("mUuid", building.uuid.toString())
      newData.putString("pUuid", player.uuid.toString())
      newData.putString(`team`, `${team}`)
      newTD.mergeNbt(`{OwnerUUID:${pUUID}}`)
      newTD.addTag("snk_td_registered")

      // 使用函数方法设置属性加成
      global.AttributeEnhancement(newTD, "hundred_years_war:ranged_attack_damage", "td_damage", 0.3, 1)
      global.AttributeEnhancement(newTD, "minecraft:generic.max_health", "td_health", 200, 0)
      global.AttributeEnhancement(newTD, "minecraft:generic.movement_speed", "td_speed", -1, 1)

      server.runCommandSilent(`execute as ${newTD.uuid.toString()} run team join ${team} @s`)
      newTD.setHealth(99999)
      player.tell(`${config.displayName}已完成组装！`)
    }
    if (building.tags.contains("snk_archer_defense")) {
      let check = true
      server.entities.forEach((defense) => {
        if (
          defense.tags.contains("snk_td_registered") &&
          bUuid === defense.persistentData.getString("mUuid")
        ) {
          if (defense.type.toString() === config.entityId) {
            check = false;
            defense.teleportTo(building.level.dimension.path, mx + 0.5, my + 2, mz + 0.5, 0, 0);
          } else {
            player.tell(`§c检测到已有射手，已调离岗位`)
            defense.mergeNbt(`{Health:0,DeathTime:19}`)
          }
        }
      })
      if (check === false) {
        player.tell(`§c检测到已有相同的射手，取消雇佣`)
        return
      }
      let newTD = event.level.createEntity(config.entityId)
      let newData = newTD.persistentData
      newTD.setPosition(mx + 0.5, my + 1, mz + 0.5)
      newTD.spawn()
      newData.putString("mUuid", building.uuid.toString())
      newData.putString("pUuid", player.uuid.toString())
      newData.putString(`team`, `${team}`)
      newTD.mergeNbt({
        OwnerUUID: pUUID,
        ArmorItems: [
          { Count: 1, id: "minecraft:chainmail_boots" },
          { Count: 1, id: "minecraft:chainmail_leggings" },
          { Count: 1, id: "minecraft:chainmail_chestplate" },
          { Count: 1, id: "minecraft:chainmail_helmet" },
        ],
      });
      if (config.entityId === "hundred_years_war:archer") {
        newTD.setMainHandItem(Item.of("minecraft:bow"))
      }
      if (config.entityId === "hundred_years_war:crossbowman") {
        newTD.setMainHandItem(Item.of("minecraft:crossbow"))
      }
      newTD.addTag("snk_td_registered");

      global.AttributeEnhancement(newTD, "hundred_years_war:ranged_attack_damage", "td_damage", 1.5, 1)
      global.AttributeEnhancement(newTD, "minecraft:generic.max_health", "td_health", 100, 0)
      global.AttributeEnhancement(newTD, "minecraft:generic.movement_speed", "td_speed", -1, 1)

      server.runCommandSilent(`execute as ${newTD.uuid.toString()} run team join ${team} @s`)
      newTD.setHealth(99999)
      player.tell(`${config.displayName}已雇佣！`)
    }
  });
}
//安装火炮/雇佣射手
FTBQuestsEvents.customReward((event) => {
  Object.keys(TOWER_DEFENSE).forEach((tag) => {
    if (event.reward.tags.contains(tag)) {
      AssembleTowerDefense(event, TOWER_DEFENSE[tag])
    }
  })
})

//找回炮/召回射手
FTBQuestsEvents.customReward((event) => {
  if (!event.reward.tags.contains("snk_td_tp")) return
  let server = event.server;
  let player = event.player;
  let AABB = player.boundingBox.inflate(6, 4, 6);
  player.level.getEntitiesWithin(AABB).forEach((building) => {
    let mUuid = building.uuid.toString();
    let [mx, my, mz] = building.persistentData.getIntArray("TD_pos");
    server.entities.forEach((td) => {
      if (
        td.tags.contains("snk_td_registered") &&
        mUuid === td.persistentData.getString("mUuid")
      ) {
        td.teleportTo(building.level.dimension.path, mx + 0.5, my + 1, mz + 0.5, 0, 0)
        if (building.tags.contains("snk_artillery_defense")) {
          player.tell(`属于此基座的器械已运回`);
        }
        if (building.tags.contains("snk_archer_defense")) {
          player.tell(`射手已返回岗位`);
        }
      }
    })
  })
})

//维修炮
FTBQuestsEvents.customReward((event) => {
  if (!event.reward.tags.contains("snk_td_maintain")) return
  let server = event.server
  let player = event.player
  let AABB = player.boundingBox.inflate(6, 4, 6)
  player.level.getEntitiesWithin(AABB).forEach((building) => {
    let mUuid = building.uuid.toString()
    let [mx, my, mz] = building.persistentData.getIntArray("TD_pos")
    server.entities.forEach((td) => {
      if (
        td.tags.contains("snk_td_registered") &&
        mUuid === td.persistentData.getString("mUuid")
      ) {
        td.teleportTo(building.level.dimension.path, mx + 0.5, my + 1, mz + 0.5, 0, 0)
        player.tell(`属于此基座的器械已运回`)

        let costs = [{ id: "minecraft:amethyst_shard", count: 12 }]
        if (!global.ConsumableItems(player, costs)) return

        td.setHealth(9999)
        player.tell(`器械已修复`)
      }
    })
  })
})