minetest.register_node("ikea_tools:flashlight_light", {
	description = "Flashlight Light",
	drawtype = "airlike",
	paramtype = "light",
	light_source = minetest.LIGHT_MAX,
	buildable_to = true,
	floodable = true,
	pointable = false,
	walkable = false,

	on_timer = function(pos, elapsed)
		minetest.swap_node(pos, {name = "air"})
	end,
})

local function flashlight_update(name)
	local player = minetest.get_player_by_name(name)
	if not player then
		return
	end

	local wielded_item = player:get_wielded_item()
	if wielded_item:get_name() ~= "ikea_tools:flashlight_on" then
		local inv = player:get_inventory()
		inv:set_stack("main", 1, ItemStack("ikea_tools:flashlight_off"))
		return
	end

	local pos = player:get_pos()
	pos.y = pos.y + (player.eye_height or 1.625)
	local look_dir = player:get_look_dir()

	local light_pos
	for pointed_thing in Raycast(pos, pos + (look_dir * 500), true, true) do
		if (pointed_thing.type == "object") and (pointed_thing.ref ~= player) then
			light_pos = pointed_thing.ref:get_pos() + {x = 0, y = 1, z = 0}
			break
		elseif pointed_thing.type == "node" then
			light_pos = pointed_thing.above
			break
		end
	end

	if light_pos then
		local node_name = minetest.get_node(light_pos).name

		if node_name == "air" then
			minetest.swap_node(light_pos, {name = "ikea_tools:flashlight_light"})
			-- Sometimes nodeboxes and meshes can throw this off
			-- so try one block closer to the player
		elseif node_name ~= "ikea_tools:flashlight_light" then
			light_pos = light_pos - vector.round(look_dir)
			node_name = minetest.get_node(light_pos).name
			if node_name == "air" then
				minetest.swap_node(light_pos, {name = "ikea_tools:flashlight_light"})
			end
		end

		if (node_name == "air") or (node_name == "ikea_tools:flashlight_light") then
			minetest.get_node_timer(light_pos):start(0.3)
		end
	end

	minetest.after(0.2, flashlight_update, name)
end

minetest.register_node("ikea_tools:flashlight_off", {
	description = "Flashlight (off)",
	drawtype = "mesh",
	mesh = "ikea_tools_flashlight_off.obj",
	tiles = {"ikea_tools_flashlight_off.png"},
	range = 0,

	on_secondary_use = function(itemstack, user, pointed_thing)
		itemstack:replace("ikea_tools:flashlight_on")
		minetest.after(0, flashlight_update, user:get_player_name())
		return itemstack
	end,
})

minetest.register_node("ikea_tools:flashlight_on", {
	description = "Flashlight (on)",
	drawtype = "mesh",
	mesh = "ikea_tools_flashlight_on.obj",
	tiles = {"ikea_tools_flashlight_on.png"},
	range = 0,

	on_secondary_use = function(itemstack, user, pointed_thing)
		itemstack:replace("ikea_tools:flashlight_off")
		return itemstack
	end,
})
