local player_pos = {}
local player_pos_previous = {}

local math = math

minetest.register_on_joinplayer(function(player)
	local player_name = player:get_player_name()
	player_pos_previous[player_name] = { x=0, y=0, z=0 }
end)

minetest.register_on_leaveplayer(function(player)
	local player_name = player:get_player_name()
	player_pos_previous[player_name] = nil
end)

minetest.register_on_mods_loaded(function()
	for k,v in pairs(minetest.registered_nodes) do
		if v._footsteps and v._footsteps_name then
			minetest.override_item(k, {
				on_timer = function(pos)
					local node = minetest.get_node(pos)
					node.name = v._footsteps_name
					minetest.swap_node(pos, node)
				end,
			})
		end
	end
end)

-- Chance to change is odd of 100
local odd = 75
local timer = 0

minetest.register_globalstep(function(dtime)
	-- Don't check all the time.
	timer = timer + dtime
	if timer < 3 then return end
	timer = 0

	for _,player in pairs(minetest.get_connected_players()) do
		if math.random(1, 100) > odd then return end
		local pos = player:get_pos()
		local player_name = player:get_player_name()
		player_pos[player_name] = { x=math.floor(pos.x+0.5), y=math.floor(pos.y+0.5), z=math.floor(pos.z+0.5) }
		local p_ground = { x=math.floor(pos.x+0.5), y=math.floor(pos.y), z=math.floor(pos.z+0.5) }
		local n_ground  = minetest.get_node(p_ground)

		-- Check if position is the previous position
		if player_pos_previous[player_name] == nil then
			return
		end

		if player:get_player_control().sneak then
			return
		end

		if	player_pos[player_name].x == player_pos_previous[player_name].x and
			player_pos[player_name].y == player_pos_previous[player_name].y and
			player_pos[player_name].z == player_pos_previous[player_name].z
		then
			return
		end

		local def_ground = minetest.registered_nodes[n_ground.name]
		if not def_ground then return end

		-- Make footsteps
		if def_ground._footsteps_name then
			local new_node
			if not def_ground._footsteps then
				new_node = def_ground._footsteps_name
			else
				new_node = n_ground.name
			end
			minetest.swap_node(p_ground, {type="node", name=new_node})
			minetest.get_node_timer(p_ground):start(math.random(3, 48))
			minetest.sound_play(def_ground.sounds.footstep,
				{pos = pos, max_hear_distance = 16, gain = 0.25})
		end

		-- Make position to previous position
		player_pos_previous[player_name] =  player_pos[player_name]
	end
end)

minetest.register_lbm({
	name = "footsteps:convert_footsteps_to_node_timer",
	nodenames = {"default:dirt_with_grass_footsteps"},
	action = function(pos)
		minetest.get_node_timer(pos):start(math.random(3, 48))
	end
})

dofile(minetest.get_modpath("footsteps").."/nodes.lua")
