-- Compass mod
-- Code: by Astrobe, MIT license.
-- Texture: taken from the "Magic compass" mod by Zughy, CC BY-SA 4.0.

local st=minetest.get_mod_storage()
local playerwp={}

local function update_wp(name, pos)
	if not name then return end
	local player=minetest.get_player_by_name(name)
	if not player then return end
	if playerwp[name] then
		player:hud_remove(playerwp[name])
		playerwp[name]=nil
	end
	if pos then
		playerwp[name]=player:hud_add {
			type="waypoint",
			name="+",
			number=0x808080,
			precision=1,
			world_pos=pos }
	end
end

compass=
{
	get_wp2=function(name)
		if not playerwp[name] then return nil end
		return minetest.deserialize(st:get_string(name))
	end,
	set_wp2=function(name, pos)
		st:set_string(name, minetest.serialize(pos))
		update_wp(name, pos)
	end

}


minetest.register_on_joinplayer(function(player)
	local name=player:get_player_name()
	local p=minetest.deserialize(st:get_string(name))
	if p then update_wp(name, p) end
	end)


local zero=vector.new(0,0,0)
local detect_fx=function(pos)
	minetest.add_particlespawner
	{
		amount=200,
		time=20,
		minpos=pos,
		maxpos=pos,
		minvel={x=-6,y=-6,z=-6},
		maxvel={x=6,y=6,z=6},
		minacc=zero,
		maxacc=zero,
		minsize=4,
		maxsize=4,
		glow=7,
		texture="default_mineral_mese.png",
		-- playername=player:get_player_name()
	}
end

minetest.register_craftitem("compass:compass", {
	description = "Compass.\nDetects nearby ores when activated, shows heading, time and date.\nGet: from lootboxes.\nSingle-use.",
	inventory_image = "compass.png",
	sound = {breaks = "default_tool_breaks"},
	groups={not_repaired_by_anvil=1},
	on_use=function(itemstack, player)
		local name=player:get_player_name()
		local t=minetest.get_timeofday()*1440
		local bearing=math.floor(player:get_look_horizontal()*180/math.pi)
		minetest.chat_send_player(name,"Bearing: "..bearing.." Altitude: "..math.floor(player:get_pos().y)..string.format(" Time: Moon %d, %02d:%02d",minetest.get_day_count(), t/60,t%60).." Light level: "..minetest.get_node_light(player:get_pos()))

		local pos=player:get_pos()
		local vol=5
		local p1={x=pos.x-vol, y=pos.y-vol, z=pos.z-vol}
		local p2={x=pos.x+vol, y=pos.y+vol, z=pos.z+vol}
		for _,ore in ipairs(minetest.find_nodes_in_area(p1, p2, "group:ore")) do
			detect_fx(ore)
		end
		local plava=minetest.find_node_near(pos, vol, "default:lava_source")
		if plava then detect_fx(plava) end
		itemstack:take_item()
		return itemstack
	end,
})

