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

local spread_per_step = 0
local max_spread_per_step = 100

local adjacent = {
    [0] = vector.new( 0,-1, 0),
    [1] = vector.new( 0, 1, 0),
    [2] = vector.new( 1, 0, 0),
    [3] = vector.new(-1, 0, 0),
    [4] = vector.new( 0, 0, 1),
    [5] = vector.new( 0, 0,-1),
}
local function has_adjacent(pos, group)
    local count = 0
    local node
    for i, offset in pairs(adjacent) do
        local p = vector.add(pos, offset)
        local n = minetest.get_node(p).name
        if n == group or minetest.get_item_group(n, group) ~= 0 then
            count = count + 1
            if not node then
                node = minetest.get_node(p)
            end
        end
    end
    return count, node
end


local function start_timer(pos, cause, user, count)
    local nt = minetest.get_node_timer(pos)
    nt:start(3)
    nt:set(2, math.random()*2)
    return false
end

local function spread(pos)
    minetest.set_timeofday(0.2)
    local node = minetest.get_node(pos)
    if node.name == "penumbra:n" then
        minetest.set_node(pos, {name="air"})
        return false
    else
        minetest.set_node(pos, {name="penumbra:n"})
    end

    -- if spread_per_step > max_spread_per_step then return true end
    for i=0, #adjacent do
        local p = vector.add(pos, adjacent[i])
        local n = minetest.get_node(p).name
        if minetest.get_item_group(n, "penumbra") == 0
        and (n ~= "air" or math.random() < 0.1) then
            minetest.set_node(p, {name="penumbra:a"})
            spread_per_step = spread_per_step + 1
            start_timer(p, "penumbra")
        end
    end
end

minetest.register_node('penumbra:a', {
    description = 'Dirt',
    groups = { solid = 1, full_solid = 1, penumbra = 1 },
    tiles = { 'penumbra_a.png' },
    sounds = {},
    on_timer = spread,
    _on_node_update = start_timer,
    light_source = 4,
})

minetest.register_node('penumbra:n', {
    description = 'Dirt',
    groups = { solid = 1, full_solid = 1, penumbra = 1 },
    tiles = { 'penumbra_n.png' },
    sounds = {},
    on_timer = spread,
    _on_node_update = start_timer,
})

local function on_step(dtime)
    spread_per_step = 0
end
minetest.register_globalstep(on_step)

