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

aom_mob_spawn = {
               enabled = false,
            spawn_dist = {min=30, max=110}, -- spawns can happen in this range
    despawn_dist_force = 128, -- mobs always despawn at this dist
          despawn_dist = 70, -- mobs sometimes despawn at this dist
        despawn_chance = 0.03,
                mobcap = 100, -- hard max for all mobs of any type
          spawn_rarity = 1, -- per second
           spawn_tries = 5, -- tries per sec
               version = 1
}

local has_aom_settings = (core.get_modpath("aom_settings") ~= nil)
function aom_mob_spawn.get_setting(p, n, d)
    if has_aom_settings then
        return aom_settings.get_setting(p, n, d)
    else
        return d
    end
end

if has_aom_settings then
    local world_ver = age_of_mending.version.first_for_world
    aom_settings.register_setting("mob_spawning_enabled", true, S("Mob Spawning Enabled"), "server")
    --#todo: implement full replacement of old spawning system
    aom_settings.register_setting("mob_spawn_old", (false and world_ver < 58), S("Old Mob Spawning Enabled"), "server")
    aom_settings.register_setting("mob_hostile_max", 100, S("Max Hostile Mob Cap"), "server")
    aom_settings.register_setting("mob_hostile_grace_time", 20, S("Hostile Mob Spawn Grace Period (in minutes)"), "server")
    aom_mob_spawn.enabled = aom_settings.get_setting(nil, "mob_spawning_enabled", true)
    aom_settings.register_on_change_setting("mob_spawning_enabled", function(player, settingname, new_value, old_value)
        aom_mob_spawn.enabled = new_value
    end)
end

-- contains all grouped caps
aom_mob_spawn.cap = {
        all = {max = 100, cur = 0},
    hostile = {max = 0, cur = 0}, -- modified on the fly with `core.get_gametime()`
    passive = {max = 20, cur = 0},
}

dofile(mod_path .. "/spawn_rule_register.lua")
dofile(mod_path .. "/spawn_rule_helpers.lua")
dofile(mod_path .. "/spawner.lua")

core.register_chatcommand("mob_spawning", {
    params = "",
    description = S("Turns on or off mob spawning"),
    privs = { server = 1 },
    func = function(name, param)
        if param == "off" then
            aom_mob_spawn.enabled = false
            if has_aom_settings then aom_settings.set_setting(nil, "mob_spawning_enabled", false) end
        elseif param == "on" then
            aom_mob_spawn.enabled = true
            if has_aom_settings then aom_settings.set_setting(nil, "mob_spawning_enabled", true) end
        else
            return true, "Mob spawning for this world is currently |" ..
            ((aom_mob_spawn.enabled and "enabled") or "disabled") .. "|"
        end
        return true, "Mob spawning for this world has been set to |" ..
        ((aom_mob_spawn.enabled and "enabled") or "disabled") .. "|"
    end
})
