local utf8 = require("utf8")

local function backspace(text)
	local byteoffset = utf8.offset(text, -1)

	if byteoffset then
		-- remove the last UTF-8 character.
		-- string.sub operates on bytes rather than UTF-8 characters,
		-- so we couldn't do string.sub(text, 1, -2).
		return string.sub(text, 1, byteoffset - 1)
	end

	return ""
end

Prompt = class(nil, {
	-- defaults for instance variables
	pos = { x = 10, y = 10 },
	input = "",
	name = "input",
	canceled = false,
	closing = false,
	color = {1,1,1,1},
	background_color = {0,0,0,1},
	active_prompt = nil,
})
function Prompt:cancelActive()
	if Prompt.active_prompt then
		Prompt.active_prompt.canceled = true
	end
end

function Prompt:new(o)
	o = o or {}
	setmetatable(o, self)
	return o
end

function Prompt:keypressed(key, scancode, isrepeat)
	if key == "backspace" then
		self.input = backspace(self.input)
	elseif key == "return" or key == "kpenter" or key == "escape" then
		if key == "escape" then
			self.canceled = true
		end
		self.closing = true
		self:func()
	end
end

function Prompt:update()

end

function Prompt:textinput(text)
	self.input = self.input .. text
end

function Prompt:draw()
	drawTextBox(
		self.name .. ": " .. self.input,
		self.pos.x,
		self.pos.y,
		{
			color = self.color,
			background_color = self.background_color
		}
	)
end

function Prompt:activate()
	Prompt.active_prompt = self
	love.keyboard.setTextInput(true)
end

-- demonstration of how default values work
local test_prompt = Prompt:new()
assert(test_prompt.name == "input")
test_prompt.name = "foobar"
assert(Prompt.name == "input")
