-- LUALOCALS < ---------------------------------------------------------
local klots, minetest, vector
    = klots, minetest, vector
-- LUALOCALS > ---------------------------------------------------------

if klots.editmode then return end

local modname = minetest.get_current_modname()

local crosshair_opacity = 32
local actuate_opacity = 128

local function playercast(player)
	local pos = player:get_pos()
	pos.y = pos.y + player:get_properties().eye_height
	local look = player:get_look_dir()
	local target = vector.add(pos, vector.multiply(look, 4))
	for pt in minetest.raycast(pos, target, false, false) do
		if pt.type == "node" then
			return pt
		end
	end
end

local function settip(player, data, pos)
	if not pos then
		if data.hud then
			player:hud_remove(data.hud)
			data.hud = nil
		end
		return
	end
	if not data.hud then
		data.hud = player:hud_add({
				hud_elem_type = "image_waypoint",
				world_pos = pos,
				text = modname .. "_actuate.png^[opacity:"
				.. actuate_opacity,
				scale = {x = 1, y = 1},
				precision = 0,
				number = 0xffffff,
				z_index = -250,
				alignment = {x = 0, y = 0}
			})
		data.pos = pos
	elseif not vector.equals(data.pos, pos) then
		player:hud_change(data.hud, "world_pos", pos)
		data.pos = pos
	end
end

local function nodeface(pt)
	return vector.multiply(vector.add(
			pt.under, pt.above), 0.5)
end

klots.register_playerstep(function(player, data)
		local pt = playercast(player)
		if not pt then return settip(player, data) end
		local node = minetest.get_node(pt.under)
		local def = minetest.registered_nodes[node.name]
		if def and def.on_actuate then
			return settip(player, data, nodeface(pt))
		end
		return settip(player, data)
	end)

minetest.register_on_joinplayer(function(player)
		player:hud_set_flags({crosshair = false})
		player:hud_add({
				hud_elem_type = "image",
				position = {x = 0.5, y = 0.5},
				text = modname .. "_crosshair.png^[opacity:"
				.. crosshair_opacity,
				direction = 0,
				scale = {x = 1, y = 1},
				offset = {x = 0, y = 0}
			})
	end)
