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


aom_wire.debug_enable = false
local debugtags = {
    all = true
}

function aom_wire.debug(tag, text, color)
    if not text then text = tag; tag = nil end
    if not aom_wire.debug_enable then return end
    if not debugtags[tag or "all"] then return end
    if color then text = minetest.colorize(color, text) end
    minetest.log(text)
end


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

function aom_wire.dist2(p1, p2)
    return (p1.x-p2.x)^2 + (p1.y-p2.y)^2 + (p1.z-p2.z)^2
end

function aom_wire.add_output(pos, target, max_targets)
    -- target = {x=target.x, y=target.y, z=target.z}
    local meta = minetest.get_meta(pos)
    if not meta then
        aom_wire.debug("info", "no meta")
        return false
    end
    -- by definition, can only link from output nodes
    local datastring = meta:get_string("aom_wire_target")
    local data = ((datastring ~= "") and minetest.deserialize(datastring, true)) or {}
    if #data >= max_targets then
        aom_wire.debug("info", "too many outputs already")
        return false
    end
    local has_already = false
    for k, v in ipairs(data) do
        if vector.equals(v, target) then
            aom_wire.debug("info", "already stored")
            has_already = true
            table.remove(data, k)
            break
        end
    end
    if not has_already then
        table.insert(data, target)
    end
    meta:set_string("aom_wire_target", minetest.serialize(data))
    aom_wire.debug("info", "stored")
    return true
end

function aom_wire.get_outputs(pos)
    local meta = minetest.get_meta(pos)
    if not meta then
        aom_wire.debug("info", "no meta")
        return nil
    end
    local datastring = meta:get_string("aom_wire_target")
    local data = ((datastring ~= "") and minetest.deserialize(datastring, true)) or nil
    return data
end
