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

lzr_level_select = {}

local current_level_selection = nil
lzr_level_select.open_dialog = function(player)
	local form = "formspec_version[4]size[6,10]"..
		"label[0.5,0.4;"..F(S("Select level:")).."]"..
		"button_exit[1.5,8.5;3,1;okay;"..F(S("Start")).."]"..
		"tablecolumns[color;text]"..
		"table[0.5,0.8;5,7.5;levellist;"
	local list = {}
	local entry_header = ""
	local completed_levels = lzr_levels.get_completed_levels()
	local first_uncompleted_level = nil
	for l=1, lzr_levels.LAST_LEVEL do
		if completed_levels[l] then
			entry_header = "#00FF00"
		else
			if not first_uncompleted_level then
				first_uncompleted_level = l
			end
			entry_header  = ""
		end
		table.insert(list, entry_header..","..F(lzr_levels.get_level_name(l)))
	end
	if not first_uncompleted_level then
		first_uncompleted_level = 1
	end
	current_level_selection = first_uncompleted_level
	local list_str = table.concat(list, ",")
	form = form .. list_str .. ";"..first_uncompleted_level.."]"
	minetest.show_formspec(player:get_player_name(), "lzr_level_select:levellist", form)
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
	if formname == "lzr_level_select:levellist" then
		if fields.okay then
			if current_level_selection then
				lzr_levels.start_level(current_level_selection)
			end
		elseif fields.levellist then
			local expl = minetest.explode_table_event(fields.levellist)
			if expl.type == "CHG" then
				current_level_selection = expl.row
			elseif expl.type == "DCL" then
				current_level_selection = expl.row
				lzr_levels.start_level(current_level_selection)
				minetest.close_formspec(player:get_player_name(), "lzr_level_select:levellist")
			elseif expl.type == "INV" then
				current_level_selection = nil
			end
		end
	end
end)

minetest.register_chatcommand("level", {
	privs = { server = true },
	description = S("Go to level"),
	params = S("<level>"),
	func = function(name, param)
		local level = tonumber(param)
		if not level then
			return false
		end
		if level < 1 or level > lzr_levels.LAST_LEVEL then
			return false, S("Invalid level!")
		end
		lzr_levels.start_level(level)
		return true
	end,

})

