local stdout
if DEBUG stdout = io.open("logs/client.log",IO.WRITE) end
local cons = {
	scroll = 0,
	scroll_dir = false,
	speed = 8,
	lines = {}
}

function console.reset()
	cons.scroll = 0
	cons.scroll_dir = false
end

function console.print(line)
	-- TODO: line wrapping and newline handling.
	line = tostring(line)
	table.insert(cons.lines,1,line)
	if DEBUG stdout:putstr(line.."\n") end
end

function console.think()
	if input.btn_start & 1<<BTN.LOG ~= 0
		cons.scroll_dir = not cons.scroll_dir
	end
	if cons.scroll_dir and cons.scroll < graphics[Console]:h()
		cons.scroll = cons.scroll + cons.speed
	elseif not cons.scroll_dir and cons.scroll > 0
		cons.scroll = cons.scroll - cons.speed
	end
	if cons.scroll > graphics[Console]:h()
		cons.scroll = graphics[Console]:h()
	end
end

function console.draw(screen)
	if cons.scroll > 0
		screen.draw(graphics[Console],{0,graphics[Console]:h()-cons.scroll,320,cons.scroll},{0,0})
		local font_height = 5
		local y = cons.scroll-font_height-4
		local started
		for i,v in ipairs(cons.lines)
			if v == '' and not started
				continue
			end
			started = true
			font.draw_string(screen,v,4,y,"hd")
			y = y - font_height
			if y < -font_height
				break
			end
		end
	end
end
