-- IndustrialTest
-- Copyright (C) 2024 mrkubax10

-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.

-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.

-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

-- \brief Sets uses metadata value depending on item's definition
-- \param itemstack ItemStack which should be altered
-- \returns true if value was successfully added, false otherwise
function industrialtest.api.prepareToolItem(itemstack)
	local def=minetest.registered_tools[itemstack:get_name()]
	if not def then
		return false
	end
	if def._industrialtest_tool and def.tool_capabilities and def.tool_capabilities.uses then
		local meta=itemstack:get_meta()
		meta:set_int("industrialtest.uses",def.tool_capabilities.uses)
		return true
	elseif def.groups and def.groups._industrialtest_emptyOnConstruct and itemstack:get_wear()==0 then
		itemstack:set_wear(65534)
		return true
	end
	return false
end

-- \brief Adds wear to item after it's use
-- \param itemstack ItemStack to which wear should be added
-- \returns nil
function industrialtest.api.afterToolUse(itemstack)
	local meta=itemstack:get_meta()
	local def=minetest.registered_tools[itemstack:get_name()]
	if not def or not def._industrialtest_tool or not def.tool_capabilities or not def.tool_capabilities.uses then
		return
	end
	if not meta:contains("industrialtest.uses") then
		industrialtest.prepareToolItem(itemstack)
	end
	local uses=meta:get_int("industrialtest.uses")-1
	if uses==0 then
		itemstack:set_count(0)
		minetest.sound_play({name="default_tool_breaks"},{
			gain=1,
			fade=0,
			pitch=1
		},true)
		return
	end
	meta:set_int("industrialtest.uses",uses)
	itemstack:set_wear(65535-uses/def.tool_capabilities.uses*65535)
end