local ui = {}

ui.relevantKeys = { "return", "up", "down" }

ui.height = 240
ui.fullMessage = ""
ui.active = false

ui.border = 10

ui.textLines = {}
ui.startLine = 1
ui.endLine = 1

local font = love.graphics.newFont("assets/ui/font.ttf", 24)
love.graphics.setFont(font)

ui.windowWidth = love.graphics.getWidth()
ui.windowHeight = love.graphics.getHeight()

function ui:showMessage(message)
  ui.active = true

  local maxLines = math.floor((ui.height - ui.border) / font:getHeight())
  local fullLines = font:getWrap(ui.fullMessage,  ui.windowWidth - ui.border)
  
  ui.textLines = {}
  
  local fullIndex = 1
  local messageTail = message
  
  while not endsWith(messageTail, ui.textLines[#ui.textLines]) do
    fullIndex, line, messageTail = ui:getMaxString(string.sub(messageTail, fullIndex))
    fullIndex = fullIndex + 1 -- account for the following space

    table.insert(ui.textLines, line)
  end

  ui.endLine = maxLines
  
  ui:setLineRange(ui.startLine, ui.endLine)
end

function ui:setLineRange(startLine, endLine)
  ui.fullMessage = ""
  
  if endLine > #ui.textLines then endLine = #ui.textLines end

  for index = startLine, endLine, 1 do
    ui.fullMessage = ui.fullMessage .. ui.textLines[index]
  end
end

function endsWith(s, send)
  if not send then return false end
  return #s >= #send and s:find(send, #s-#send+1, true) and true or false
end

function ui:getMaxString(stringTail)
  local index = string.len(stringTail)
  local width = font:getWidth(string.sub(stringTail, 1, index))

  local needsCutting = width >  ui.windowWidth - ui.border
  
  while width > ui.windowWidth - ui.border do
    width = font:getWidth(string.sub(stringTail, 1, index))
    index = index - 1
  end

  if needsCutting and 
     string.sub(stringTail, index + 1, index + 1) ~= " " then
    local cursor = "!"
    while cursor ~= " " and cursor ~= "" do
      index = index - 1
      cursor = string.sub(stringTail, index, index)
    end
  end

  return index, string.sub(stringTail, 1, index), stringTail
end

function ui:draw()
  if ui.active then
    love.graphics.setColor(255, 255, 255, 150)
    love.graphics.rectangle("fill", 0, ui.windowHeight - ui.height,  ui.windowWidth, ui.height)

    love.graphics.setColor(55, 60, 60, 255)
    love.graphics.printf(ui.fullMessage, ui.border, ui.windowHeight - ui.height + ui.border, ui.windowWidth - ui.border)
  end
end

function ui:sendKey(key)
  if key == "up" then
    if ui.startLine > 1 then
      ui.startLine = ui.startLine - 1
      ui.endLine = ui.endLine - 1
      
      ui:setLineRange(ui.startLine, ui.endLine)
    end
  end
  
  if key == "down" then
    if ui.endLine < #ui.textLines then
      ui.startLine = ui.startLine + 1
      ui.endLine = ui.endLine + 1
      
      ui:setLineRange(ui.startLine, ui.endLine)
    end
  end
  
  if key == "return" then
    ui.active = false
  end
end

return ui
