
local adjacent = {
    vector.new( 0, 1, 0),
    vector.new( 0,-1, 0),
    vector.new( 0, 0, 1),
    vector.new( 0, 0,-1),
    vector.new( 1, 0, 0),
    vector.new(-1, 0, 0),
}

local function get_next_adjacent(pos)
    for i, p in ipairs(adjacent) do
        local pp = pos + p
        local node = minetest.get_node(pp)
        if minetest.get_item_group(node.name, "full_solid") > 0 then
            return pp
        end
    end
end

function pmb_lights.has_floor(pos)
    local solid_below = pmb_util.has_pointable_node_at(vector.offset(pos, 0, -0.51, 0), "solid")
    if solid_below then return true end
end

function pmb_lights.has_ceiling(pos)
    local solid_above = pmb_util.has_pointable_node_at(vector.offset(pos, 0, 0.51, 0), "solid")
    if solid_above then return true end
end

function pmb_lights.fix_wall_floor_placement(pos)
    local node = minetest.get_node(pos)
    local ndef = minetest.registered_nodes[node.name]
    local has_floor = pmb_lights.has_floor(pos)
    local has_ceiling = pmb_lights.has_ceiling(pos)
    if (has_floor) and ndef._floor and (node.name ~= ndef._floor) then
        node.name = ndef._floor
        node.param2 = 0
        minetest.swap_node(pos, node)
    elseif (not has_floor) and ndef._wall and (node.name ~= ndef._wall) then
        node.name = ndef._wall
        minetest.swap_node(pos, node)
    elseif (has_ceiling) and ndef._ceiling and (node.name ~= ndef._ceiling) then
        node.name = ndef._ceiling
        minetest.swap_node(pos, node)
    end
    if (not has_floor) and ndef._wall then
        local dir = minetest.facedir_to_dir(node.param2)
        local p = pos + dir
        local n = minetest.get_node(p)
        if dir.y == 1 then
            minetest.dig_node(pos)
            return
        end
        if minetest.get_item_group(n.name, "full_solid") <= 0 then
            if not pmb_util.rotate_to_any_walkable(pos) then
                minetest.dig_node(pos)
                return
            end
        end
    end
    if ndef._no_wall and (not has_ceiling) and (not has_floor) then
        minetest.dig_node(pos)
    end
end

function pmb_lights.on_node_update(pos, cause, user, count, payload)
    pmb_lights.fix_wall_floor_placement(pos)
end
