local mod_name = minetest.get_current_modname()
local mod_path = minetest.get_modpath(mod_name)
local S = minetest.get_translator(mod_name)

if minetest.get_modpath("aom_mob_spawn") then
    local nodes = {
        ["aom_stone:cobble_moss_1"] = true,
        ["aom_stone:cobble_moss_2"] = true,
        ["aom_mirecaves:stone_moss"] = true,
        ["aom_soil:forest_dirt"] = true,
        ["aom_soil:forest_grass_1"] = true,
        ["aom_soil:forest_grass_2"] = true,
        ["aom_soil:gravel"] = true,
    }
    local biomes = {
        ["boulder_valley"] = true,
        ["boulder_valley_OCEAN"] = true,
        ["siera_mountains"] = true,
        ["siera_plains"] = true,
        ["siera_plains_OCEAN"] = true,
    }
    aom_mob_spawn.register_mob({
        name = "aom_goblins:goblin",
        groups = {"hostile"},
        biomes = {},
        on_spawn = function(self, pos)
            for i = 0, (math.random(1,4)) do
                local spos = vector.offset(
                    pos,
                    (math.random()*2-1) * 0.4,
                    0.4,
                    (math.random()*2-1) * 0.4
                )
                local obj = minetest.add_entity(spos, "aom_goblins:goblin")
                obj:set_yaw(math.random() * math.pi * 2)
                obj:add_velocity(vector.new(
                    (math.random()*2-1) * 8,
                    1,
                    (math.random()*2-1) * 8
                ))
            end
        end,
        can_spawn = function(pos, spawn_info)
            if not aom_dimensions.is_in("overworld", pos) then return false end
            if not aom_mob_spawn.has_head_room(pos, 2) then return false end
            -- not near artificial light, not in sunlight
            local node = minetest.get_node(vector.offset(pos, 0, -1, 0))
            local is_dark = aom_mob_spawn.has_light(pos, 0, 2, nil)

            if nodes[node.name] then
                if is_dark then
                    return aom_entity_api.has_mobs_in_radius(pos, 80, {"aom_goblins:goblin"}, 0, 0)
                end
            end
            if (is_dark or (math.random() < 0.05)) and biomes[spawn_info.biome_name] then
                return aom_entity_api.has_mobs_in_radius(pos, 140, {"aom_goblins:goblin"}, 0, 3)
            end
            return false
        end,
        can_despawn = function(self)
            if self._age and self._age < 120 then return false end
            return true
        end,
    })
end
