-- LUALOCALS < ---------------------------------------------------------
local math, minetest, pairs, piredo_items, posrel
    = math, minetest, pairs, piredo_items, posrel
local math_floor
    = math.floor
-- LUALOCALS > ---------------------------------------------------------

local function rotate(v, rot)
	return math_floor(v / 4) * 4 + rot[(v % 4) + 1]
end

local function doorchange(x, y, rot)
	local function toggle(pos, node)
		node.name = y
		node.param2 = rotate(node.param2, rot)
		minetest.swap_node(pos, node)
		minetest.sound_play("doors_door_open", {pos = pos}, true)
	end
	minetest.override_item(x, {
			on_punch = toggle,
			on_rightclick = toggle
		})
end

local function doortoggle(pref, a, b, rota, rotb)
	doorchange(pref .. a, pref .. b, rota)
	doorchange(pref .. b, pref .. a, rotb)
end

doortoggle("piredo_terrain:doors__door_wood_", "a", "b", {1, 2, 3, 0}, {3, 0, 1, 2})
doortoggle("piredo_terrain:doors__door_wood_", "c", "d", {3, 0, 1, 2}, {1, 2, 3, 0})

for k in pairs({gold = true, black = true}) do
	minetest.override_item("piredo_terrain:piranesi__door_" .. k, {
			["on_apply_key_" .. k] = function(pos, node)
				piredo_items.digeffect(pos, node)
				piredo_items.digeffect(posrel(pos)(0, 1, 0), node)
				minetest.remove_node(pos)
				minetest.sound_play("doors_steel_door_open", {pos = pos}, true)
				return ""
			end
		})
end

for old, new in pairs({open = "closed", closed = "open"}) do
	local function toggle(pos, node)
		node.name = "piredo_terrain:doors__gate_pine_wood_" .. new
		minetest.swap_node(pos, node)
		minetest.sound_play("doors_fencegate_open", {pos = pos}, true)
	end
	minetest.override_item("piredo_terrain:doors__gate_pine_wood_" .. old, {
			on_punch = toggle,
			on_rightclick = toggle
		})
end
