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

local _pl = {}
local function pl(player)
    local pi = _pl[player]
    if not pi then pi = {};_pl[player] = pi end
    return pi
end

local function send_message(player, color, message)
    core.chat_send_player(player:get_player_name(),
    S"[ruler] "..core.colorize(color, message))
end

local verts = {
    vector.new( 1, 1, 1),
    vector.new(-1, 1, 1),
    vector.new( 1, 1,-1),
    vector.new(-1, 1,-1),

    vector.new( 1, 0, 1),
    vector.new(-1, 0, 1),
    vector.new( 1, 0,-1),
    vector.new(-1, 0,-1),

    vector.new( 1,-1, 1),
    vector.new(-1,-1, 1),
    vector.new( 1,-1,-1),
    vector.new(-1,-1,-1),

    vector.new( 0, 1, 1),
    vector.new(-1, 1, 0),
    vector.new( 1, 1, 0),
    vector.new( 0, 1,-1),

    vector.new( 0,-1, 1),
    vector.new(-1,-1, 0),
    vector.new( 1,-1, 0),
    vector.new( 0,-1,-1),
}

local function set(player, p, i)
    local pi = pl(player)
    pi["pos"..i] = p
    if pi.pos1 and pi.pos2 then
        send_message(player, "#ff0", "Offset:       " .. tostring(pi.pos2 - pi.pos1))
        send_message(player, "#0ff", "Distance:  " .. tostring(vector.distance(pi.pos1, pi.pos2)))
        send_message(player, "#f0f", "Direction:  " .. tostring(vector.direction(pi.pos1, pi.pos2)))
        send_message(player, "#fff", "Size:          " .. tostring(vector.abs(pi.pos2 - pi.pos1) + vector.new(1,1,1)))
    end
    for k, d in ipairs(verts) do
        aom_admin_tools.debug_particle(p + (d * 0.51), "#fea", 1, nil, 1)
    end
    core.sound_play(("aom_admin_tools_click"), {
        gain = 0.1,
        pitch = 0.8,
        object = player,
    })
end

local function set_1(itemstack, player, pointed_thing)
    if not (pointed_thing and pointed_thing.under) then return end
    local ctrl = player:get_player_control()
    set(player, ctrl.aux1 and pointed_thing.above or pointed_thing.under, 1)
end

local function set_2(itemstack, player, pointed_thing)
    if not (pointed_thing and pointed_thing.under) then return end
    local ctrl = player:get_player_control()
    set(player, ctrl.aux1 and pointed_thing.above or pointed_thing.under, 2)
end

core.register_tool("aom_admin_tools:ruler", {
    description = S("Ruler"),
    _tt_color = "#f0f",
    _tt_how_to_use = S("[place] to select a start position.") .. "\n" ..
        S("[dig] to measure from start to the pointed node.") .. "\n" ..
        S("[aux1] to select adjacent / facing node instead.") .. "\n" ..
        S("Measurements are world-aligned."),
    inventory_image = "aom_admin_tools_ruler.png",
    wield_image = "aom_admin_tools_ruler.png",
    wield_scale = {x=0.5, y=0.5, z=1},
    groups = { admin_tools = 1, not_in_creative_inventory = 0, },
    range = 100,
    on_place = set_2,
    on_use = set_1,
})

if aom_admin_tools.has_aom_kits then
    aom_kits.add_to_kit("admin", {"aom_admin_tools:ruler"})
end
