-- LUALOCALS < ---------------------------------------------------------
local math, minetest, pairs, piredo_items, piredo_player, vector
    = math, minetest, pairs, piredo_items, piredo_player, vector
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, snd)
	local function toggle(pos, node)
		node.name = y
		node.param2 = rotate(node.param2, rot)
		minetest.swap_node(pos, node)
		minetest.sound_play(snd, {pos = pos}, true)
	end
	minetest.override_item(x, {
			on_punch = toggle,
			on_rightclick = toggle
		})
end

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

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

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_player.discover("solve:door_" .. k)
				piredo_items.digeffect(pos, node)
				piredo_items.digeffect(vector.offset(pos, 0, 1, 0), node)
				minetest.remove_node(pos)
				minetest.sound_play("doors_steel_door_open", {pos = pos}, true)
				return ""
			end,
			tiles = k == "gold"
			and {"doors_door_castle2.png^piredo_door_gold.png"} or nil
		})
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
