local S = minetest.get_translator("lzr_teleporter")
local F = minetest.formspec_escape

local open_leave_dialog = function(player)
	local levelstr = lzr_levels.get_level_name(lzr_levels.get_current_level())
	local form = "formspec_version[4]size[7,4.5]"..
		"label[0.5,0.5;"..F(S("Current level: @1.", levelstr)).."]"..
		"button_exit[2,1;3,1;continue;"..F(S("Continue")).."]"..
		"button_exit[2,2;3,1;restart;"..F(S("Restart level")).."]"..
		"button_exit[2,3;3,1;leave;"..F(S("Leave level")).."]"
	minetest.show_formspec(player:get_player_name(), "lzr_teleporter:level", form)
end

minetest.register_node("lzr_teleporter:teleporter", {
	description = S("Teleporter (on)"),
	tiles = {
		"lzr_teleporter_top.png",
		"lzr_teleporter_bottom.png",
		"lzr_teleporter_side.png",
		"lzr_teleporter_side.png",
		"lzr_teleporter_front.png",
		"lzr_teleporter_rear.png",
	},
	on_punch = function(_, _, puncher)
		if lzr_gamestate.get_state() == lzr_gamestate.LEVEL then
			open_leave_dialog(puncher)
		end
	end,
	groups = { breakable = 1, teleporter = 2 },
	sounds = lzr_sounds.node_sound_stone_defaults(),
})

minetest.register_node("lzr_teleporter:teleporter_off", {
	description = S("Teleporter (off)"),
	tiles = {
		"lzr_teleporter_off_top.png",
		"lzr_teleporter_off_bottom.png",
		"lzr_teleporter_off_side.png",
		"lzr_teleporter_off_side.png",
		"lzr_teleporter_off_front.png",
		"lzr_teleporter_off_rear.png",
	},
	on_punch = function(_, _, puncher)
		if lzr_gamestate.get_state() == lzr_gamestate.LEVEL then
			open_leave_dialog(puncher)
		end
	end,
	groups = { breakable = 1, teleporter = 1 },
	sounds = lzr_sounds.node_sound_stone_defaults(),
})

minetest.register_on_player_receive_fields(function(player, formname, fields)
	if formname == "lzr_teleporter:level" then
		if lzr_gamestate.get_state() == lzr_gamestate.LEVEL then
			if fields.leave then
				lzr_levels.leave_level()
			elseif fields.restart then
				lzr_levels.restart_level()
			end
		end
	end
end)
