PyuTest.DOOR_NODEBOX = {
	type = "fixed",
	fixed = { -0.5, -0.5, -0.38, 0.5, 1.5, -0.5 }
}

local function door_toggle_param2(start, current)
	if start == 3 and current + 1 > start then
		return start - 1
	elseif start >= 0 and current > start then
		return current - 1
	else
		return current + 1
	end
end
local DOOR_META_PARAM2_NAME = "door_start_param2"

local function after_place_node(pos, placer)
	local node = core.get_node(pos)
	local meta = core.get_meta(pos)
	meta:set_int(DOOR_META_PARAM2_NAME, node.param2)
end

local function on_rightclick(pos, node, clicker)
	local meta = core.get_meta(pos)

	core.swap_node(pos, {
		name = node.name,
		param2 = door_toggle_param2(meta:get_int(DOOR_META_PARAM2_NAME), node.param2)
	})

	core.sound_play({
		name = "pyutest_crate_open",
		gain = 1,
	}, {pos = pos})
end

local function electricity_input(pos, node, sender_pos)
	on_rightclick(pos, node)
end

PyuTest.make_door = function(name, desc, craftitem, texture, groups, extra)
	local e = extra or {}

	core.register_node(name, PyuTest.util.tableconcat({
		description = Translate(desc),
		groups = PyuTest.util.tableconcat(groups, {
			door = 1
		}),
		tiles = texture,
		sounds = PyuTest.make_node_sounds(),
		paramtype = "light",
		paramtype2 = "facedir",
		drawtype = "mesh",
		mesh = "pyutest-door.obj",

		selection_box = PyuTest.DOOR_NODEBOX,
		collision_box = PyuTest.DOOR_NODEBOX,

		after_place_node = after_place_node,
		on_rightclick = on_rightclick,
		__on_electricity_input = electricity_input,
	}, e))

	local id_windowless = name .. "_windowless"
	core.register_node(id_windowless, PyuTest.util.tableconcat({
		description = Translate("Windowless " .. desc),
		groups = PyuTest.util.tableconcat(groups, {
			door = 1
		}),
		tiles = texture,
		sounds = PyuTest.make_node_sounds(),
		paramtype = "light",
		paramtype2 = "facedir",
		drawtype = "nodebox",
		node_box = PyuTest.DOOR_NODEBOX,
		selection_box = PyuTest.DOOR_NODEBOX,
		collision_box = PyuTest.DOOR_NODEBOX,

		after_place_node = after_place_node,
		on_rightclick = on_rightclick
	}, e))

	if craftitem ~= nil then
		core.register_craft({
			output = name,
			recipe = {
				{craftitem, craftitem},
				{craftitem, craftitem},
				{craftitem, craftitem},
			}
		})

		core.register_craft({
			output = id_windowless,
			recipe = {
				name, "group:axe"
			},
			type = "shapeless"
		})
	end
end
