
pmb_wrench.pl = {}

function pmb_wrench.sort_positions(v, b)
    return vector.new(
        ((v.x <= b.x) and v.x) or b.x,
        ((v.y <= b.y) and v.y) or b.y,
        ((v.z <= b.z) and v.z) or b.z
    ),
    vector.new(
        ((v.x >= b.x) and v.x) or b.x,
        ((v.y >= b.y) and v.y) or b.y,
        ((v.z >= b.z) and v.z) or b.z
    )
end

-- returns an index list of vectors within a cube defined buy two points
function pmb_wrench.all_nodes_in(v, b)
    local list = {}
    for z=v.z, b.z do
        for y=v.y, b.y do
            for x=v.x, b.x do
                list[#list+1] = vector.new(x,y,z)
            end
        end
    end
    return list
end

function pmb_wrench.get_eyepos(player)
    local eyepos = vector.add(player:get_pos(), vector.multiply(player:get_eye_offset(), 0.1))
    eyepos.y = eyepos.y + 1.6
    return eyepos
end

function pmb_wrench.get_shell()
    return {
        name = "",
        node = {name="air"},
        build_list = nil,
        ent = {},
    }
end

function pmb_wrench.remove_all_ents(player)
    for i=1, 2 do
        if pmb_wrench.pl[player].ent[i] then
            pmb_wrench.pl[player].ent[i].object:remove()
        end
    end
end

--- end of self contained functions

--- start of dependent functions

function pmb_wrench.get_pointed_thing(player, eyepos, liquids)
    if not eyepos then eyepos = pmb_wrench.get_eyepos(player) end
    local range = (minetest.registered_tools[player:get_wielded_item():get_name()].range or 0)
    local ray = minetest.raycast(eyepos, vector.add(eyepos, vector.multiply(player:get_look_dir(), range)), false, (liquids == true))
    for pointed_thing in ray do
        if pointed_thing.type == "node" then
            return pointed_thing
        end
    end
    return nil
end

local function tex(name)
    return {name,name,name,name,name,name}
end

local entity = {
    physical = false,
    textures = tex("pmb_wrench_wrench_ENTITY.png^[colorize:#04f:100"),
    visual = "cube",
    visual_size = {x=1.1, y=1.1},
    collisionbox = {-0.2, -0.2, -0.2, 0.2, 0.2, 0.2,},
    use_texture_alpha = true,
    pointable = false,
    _parent = false,
    _timer = 1,
    _type = 1,
    glow = 14,
    on_step = function(self, dtime, moveresult)
        if self._timer < 0 then self._timer = 1
        else self._timer = self._timer - dtime return end

        if (not self._parent) or (not pmb_wrench.pl[self._parent]) or (not pmb_wrench.pl[self._parent]["pos"..self._type]) then
            self.object:remove()
            return
        end
    end,
}
minetest.register_entity("pmb_wrench:wrench_ENTITY_1", entity)
entity = table.copy(entity)
entity.textures = tex("pmb_wrench_wrench_ENTITY.png^[colorize:#ff0:100")
minetest.register_entity("pmb_wrench:wrench_ENTITY_2", entity)
