-- 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/>.

local oldInsertItemstackForRequester=logistica.insert_itemstack_for_requester

-- Logistica overrides
function logistica.insert_itemstack_for_requester(requesterPos,itemstack,limitByRequest)
	local result=oldInsertItemstackForRequester(requesterPos, itemstack, limitByRequest)

	local targetPos=logistica.get_requester_target(requesterPos)
	local def=minetest.registered_nodes[minetest.get_node(targetPos).name]
	if def._logistica_afterRequesterItemstackInsert then
		def._logistica_afterRequesterItemstackInsert(targetPos)
	end

	return result
end

local onInjectorTimer=logistica.on_timer_powered(function(pos,elapsed)
	local result=logistica.on_injector_timer(pos,elapsed)

	local targetPos=logistica.get_injector_target(pos)
	local def=minetest.registered_nodes[minetest.get_node(targetPos).name]
	if def._logistica_afterInjectorItemstackTake then
		def._logistica_afterInjectorItemstackTake(targetPos)
	end

	return result
end)

for _,name in ipairs(logistica.group_get_all_nodes_for_group("injectors")) do
	local override={
		on_timer=onInjectorTimer
	}
	minetest.override_item(name,override)
end

local function startNodeTimer(pos)
	minetest.get_node_timer(pos):start(industrialtest.updateDelay)
end

local function addLogisticaCompatibility(name)
	local override={
		_logistica_afterRequesterItemstackInsert=startNodeTimer,
		_logistica_afterInjectorItemstackTake=startNodeTimer
	}
	minetest.override_item(name,override)
end

for _,name in ipairs(industrialtest.api.tags.usesTimer) do
	addLogisticaCompatibility(name)
end