local modname = minetest.get_current_modname()
local S = minetest.get_translator(modname)

local REACTION_DELAY = 0.5

local function rotate_rules(rules, param2)
	if param2 == 0
	then
		return rules
	elseif param2 == 1
	then
		return mesecon.rotate_rules_left(rules)
	elseif param2 == 2
	then
		return mesecon.rotate_rules_left(mesecon.rotate_rules_left(rules))
	elseif param2 == 3
	then
		return mesecon.rotate_rules_right(rules)
	end
end
local rules_in =
{
	{x = 0, y = 0, z = -1}
}

local function get_rules_in(node)
	return rotate_rules(rules_in, node.param2)
end
local rules_out =
{
	{x = 0, y = 0, z = 1},
	
	{x = 0, y = -1, z = 0},
	{x = 0, y = 1, z = 0},
	
	{x = -1, y = 0, z = 0},
	{x = 1, y = 0, z = 0},
}
local function get_rules_out(node)
	return rotate_rules(rules_out, node.param2)
end

local function on_timer(pos)
	local meta = minetest.get_meta(pos)
	local node = minetest.get_node(pos)
	if meta:get_int("powered") == 0
	then
		minetest.swap_node(pos, {name = modname .. ":knot_on", param2 = node.param2})
		mesecon.receptor_on(pos, get_rules_out(node))
	else
		minetest.swap_node(pos, {name = modname .. ":knot_off", param2 = node.param2})
		mesecon.receptor_off(pos, get_rules_out(node))
	end
end

local effector =
{
	rules = get_rules_in,
	action_on = function(pos, node)
		local meta = minetest.get_meta(pos)
		meta:set_int("powered", 1)
		local timer = minetest.get_node_timer(pos)
		timer:start(REACTION_DELAY)
	end,
	action_off = function(pos, node)
		local meta = minetest.get_meta(pos)
		meta:set_int("powered", 0)
		local timer = minetest.get_node_timer(pos)
		timer:start(REACTION_DELAY)
	end,
}

local node_box =
{
	type = "fixed",
	fixed =
	{
		{-0.125, -0.5, -0.5, 0.125, -0.375, -0.125},
		{-3/16, -0.5, -0.125, 3/16, -0.25, 0.25},
	}
}

minetest.register_node(modname .. ":knot_off",
	{
		description = S("Mesecon knot"),
		tiles = {"mesecons_wire_off.png"},
		paramtype = "light",
		paramtype2 = "facedir",
		sunlight_propagates = true,
		groups = {dig_immediate = 3},
		drawtype = "nodebox",
		node_box = node_box,
		on_timer = on_timer,
		mesecons =
		{
			receptor =
			{
				state = mesecon.state.off,
				rules = get_rules_out,
			},
			effector = effector,
		},
		drop = modname .. ":knot_off",
	})

minetest.register_node(modname .. ":knot_on",
	{
		description = S("Mesecon knot"),
		tiles = {"mesecons_wire_on.png"},
		paramtype = "light",
		paramtype2 = "facedir",
		sunlight_propagates = true,
		groups = {dig_immediate = 3},
		drawtype = "nodebox",
		node_box = node_box,
		on_timer = on_timer,
		mesecons =
		{
			receptor =
			{
				state = mesecon.state.on,
				rules = get_rules_out,
			},
			effector = effector,
		},
		
	})
