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.activate_node_outputs(pos, player)
    -- go through each output
    local outputs = aom_wire.get_outputs(pos)
    for i, target in ipairs(outputs or {}) do repeat
        local n = core.get_node_or_nil(target)
        if not n then break end
        local ndef = core.registered_nodes[n.name]
        if ndef._on_wire_input ~= nil then
            ndef._on_wire_input(target, player, pos)
        end
    until true end
end

function aom_wire.activate(pos, player)
    aom_wire.activate_node_outputs(pos, player)
end

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

function aom_wire.get_outputs(pos, meta)
    meta = meta or 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
