# Run from: player/spawning/enderman_spawn_clock.mcfunction
# Run as: @s = player

scoreboard objectives add WorldSpawnClock dummy
scoreboard objectives add WorldSpawnCap dummy

# Constants
scoreboard players set .cap WorldSpawnCap 8

# Loop clock
scoreboard players set @s WorldSpawnClock 0

# Tally enderman for spawn cap
scoreboard players set .count WorldSpawnCap 0
execute as @e[type=minecraft:enderman,family=!main_island,family=forced_spawn] at @s if block ~ -64 ~ bedrock run scoreboard players add .count WorldSpawnCap 1
execute as @e[type=ldz:ender_scorcher] at @s if block ~ -64 ~ bedrock run scoreboard players add .count WorldSpawnCap 1
execute as @e[type=ldz:ender_chiller] at @s if block ~ -64 ~ bedrock run scoreboard players add .count WorldSpawnCap 1
execute as @e[type=ldz:ender_troll] at @s if block ~ -64 ~ bedrock run scoreboard players add .count WorldSpawnCap 1

# Find a spawn target
tag @e[family=mob] add SpawnPotential
tag @e[family=monster] add SpawnPotential
tag @e[tag=SpawnPotential,type=minecraft:enderman] remove SpawnPotential
tag @e[tag=SpawnPotential,family=ldz] remove SpawnPotential
# execute as @e[tag=SpawnPotential] as @s unless block ~ ~1 ~ minecraft:air unless block ~ ~2 ~ minecraft:air run tag @s remove SpawnPotential
execute if score .count WorldSpawnCap < .cap WorldSpawnCap run tag @r[type=!player,tag=SpawnPotential,tag=!HasSpawnedEnderman,r=72,rm=20] add SpawnTarget
tag @e[tag=SpawnPotential] remove SpawnPotential

# Pick a random enderman to spawn
execute at @e[tag=SpawnTarget,c=1] run summon ldz:overworld_enderman_spawner
execute as @e[tag=SpawnTarget,c=1] at @s as @e[type=ldz:overworld_enderman_spawner,r=1,c=1] at @s run function player/spawning/world_endermen/offset

## If there were no valid targets, then attempt to spawn one via spreadplayrs
execute if score .count WorldSpawnCap < .cap WorldSpawnCap unless entity @e[tag=SpawnTarget,c=1] run summon ldz:overworld_enderman_spawner
execute if score .count WorldSpawnCap < .cap WorldSpawnCap unless entity @e[tag=SpawnTarget,c=1] run spreadplayers ~ ~ 20 69 @e[type=ldz:overworld_enderman_spawner,r=1,c=1]

# Deal with target
tag @e[tag=SpawnTarget] add HasSpawnedEnderman
tag @e[tag=SpawnTarget] remove SpawnTarget

########################################################
function set_crafting_tables