hades_meshhand = {}

local handdef = minetest.registered_items[""]

-- This is a fake node that should never be placed in the world
minetest.register_node("hades_meshhand:hand", {
	description = "",
	tiles = {"hades_skins_skin_base.png"},
	use_texture_alpha = "opaque",
	visual_scale = 1,
	wield_scale = {x=1,y=1,z=1},
	paramtype = "light",
	drawtype = "mesh",
	mesh = "hades_meshhand.b3d",
	-- Prevent construction
	node_placement_prediction = "",
	on_construct = function(pos)
		minetest.log("error", "[hades_meshhand] Trying to construct hades_meshhand:hand at "..minetest.pos_to_string(pos))
		minetest.remove_node(pos)
	end,
	drop = "",
	on_drop = function()
		return ""
	end,
	-- Allow to get rid of the node if it somehow ended up in world
	buildable_to = true,
	groups = { dig_immediate = 3, not_in_creative_inventory = 1 },
	range = handdef.range,
})

minetest.register_on_joinplayer(function(player)
	player:get_inventory():set_size("hand", 1)
end)

function hades_meshhand.set_skin_color(player, colorstring)
	local hand = ItemStack("hades_meshhand:hand")
	local handmeta = hand:get_meta()
	-- WORKAROUND: Unfortunately, displaying the actual meshhand as wield image
	-- does not work due to a bug in Luanti’s lighting that causes the wrong
	-- hand color to be displayed. So instead we use a fallback image with a
	-- texture multiply, which reliably works. But this of course means the player
	-- no longer uses a true meshhand, just a regular hand texture instead.
	-- So the mesh in this mod is actually irrelevant at the moment.
	-- See <https://github.com/luanti-org/luanti/issues/12578>.
	-- TODO: Remove this workaround when above Luanti bug is fixed, and set color
	-- via the 'color' meta attribute instead.
	-- START OF WORKAROUND --
	handmeta:set_string("wield_image", "hades_meshhand_fallback.png^[multiply:"..colorstring)
	handmeta:set_string("wield_scale", vector.to_string(vector.new(1,1,3)))
	-- END OF WORKAROUND --
	player:get_inventory():set_stack("hand", 1, hand)
end

