module(..., package.seeall)

-----------------------------------------------------
-- INPUT
-----------------------------------------------------

--
-- Reads a line from stdin. If the line starts with # is ignored (a comment)
--
local function ReadInput ()
	while true do
		local input = io.read()
		if not input then error("User aborted.") end
		if not input:match("^#") then
			return input
		end
	end
end

function RequestAlpha (prompt, params)
	params = params or {}
	while true do
		io.write(prompt..(params.previous and (" (previous value: '"..params.previous.."')") or "")..(params.default and (" ["..params.default.."]") or "")..": ")
		local input = ReadInput()
		if params.default and input == "" then
			input = params.default
		end
		if not params.allowEmpty and input == "" then
			print("An empty string is not allowed for this field.")
		else
			return input
		end
	end
end

function RequestBoolean (prompt, params)
	params = params or {}
	while true do
		io.write(prompt..(params.default and " [Y/n]" or " [y/N]")..": ")
		local input = string.lower(ReadInput())
		if input == "" then
			input = params.default and "y" or "n"
		end
		if input ~= "y" and input ~= "n" then
			print("Please enter 'y' or 'n' (or leave blank for the default value).")
		else
			return (input == "y")
		end
	end
end

function RequestNumeric (prompt, params)
	params = params or {}
	while true do
		io.write(prompt..(params.previous and (" (previous value: '"..params.previous.."')") or "")..(params.default and (" ["..params.default.."]") or "")..": ")
		local input = ReadInput()
		if input == "" and params.default then
			input = tostring(params.default)
		end
		if not params.allowNull and input == "" then
			print("This field does not allow empty values.")
		elseif input == "" then
			return
		elseif not tonumber(input) then
			print("This field only allows numeric values.")
		else
			local numeric = tonumber(input)
			if not params.allowNegative and numeric < 0 then
				print("This field does not allow negative values.")
			elseif not params.allowFloat and numeric > math.floor(numeric) then
				print("This field only allows integer values.")
			else
				return numeric
			end
		end
	end
end
