-- Copyright (C) 2024 rstcxk
-- 
-- This program is free software: you can redistribute it and/or modify it under the terms of
-- the GNU Affero 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 Affero General Public License for more details.
-- 
-- You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. 

S = core.get_translator(minetest.get_current_modname())

local triggered_breakpoints = {}

local function turn_off_breakpoints()
	mcl_redstone.is_tick_frozen = false
	for _, pos in pairs(triggered_breakpoints) do
		core.set_node(pos, {name = "redstonepp:breakpoint"})
	end
end

core.register_node("redstonepp:breakpoint",
{
	paramtype = "light",
	description = S("breakpoint block"),
	tiles = {"redstonepp_breakpoint_off.png"},
	_mcl_redstone =
	{
		connects_to = function(node, dir)
			return true
		end,
		update = function(pos, node)
			if mcl_redstone.get_power(pos) > 0 then
				mcl_redstone.is_tick_frozen = true
				minetest.chat_send_all(S("breakpoint triggered at @1", tostring(pos)))
				table.insert(triggered_breakpoints, pos)
				core.swap_node(pos, {name = "redstonepp:breakpoint_on"})
			end
		end
	}
})

core.register_node("redstonepp:breakpoint_on",
{
	paramtype = "light",
	description = S("breakpoint block"),
	drop = "redstonepp:breakpoint",
	tiles = {"redstonepp_breakpoint_on.png"},
	light_source = 10,
	groups = {not_in_creative_inventory = 1},
	on_rightclick = function(pos)
		turn_off_breakpoints()
	end,
	_mcl_redstone =
	{
		connects_to = function(node, dir)
			return true
		end,
	}
})
