TextMenu = Menu:extend()

function TextMenu:new(x, y, font, slots)
  TextMenu.super.new(self, x, y, 0, 0)
  self.font       = assets:getFont(font)
  self.center     = false
  self.widgetsH   = self.font:getHeight()
  self.slots      = slots
  self.h          = self.widgetsH * self.slots
  self.begin      = 1
  self.fixedWidth = false
end

function TextMenu:centerText(width)
  self.fixedWidth = true
  self.center     = true
  self.w          = width
end

function TextMenu:update(dt)
  if (self.fixedWidth == false) then
    self:getWidth()
  end

  if self.selected < self.begin then
    self.begin = self.selected
  end
  if self.selected > self.begin + self.slots - 1 then
    self.begin = self.selected - self.slots + 1
  end

  if self.begin < 1 then
    self.begin = 1
  end
end

function TextMenu:getWidth()
  local width = self.w


  for i,v in ipairs(self.listWidget) do
    local stringWidth = self.font:getWidth(v.label)
    width = math.max(stringWidth, width)
  end

  self.w = width
end

function TextMenu:keyreleased(key, code)
  key = self.virtualpad:translateAction(1, key)

  if key == 'up' then
    self:moveCursor(self.selected - 1)
  end

  if key == 'down' then
    self:moveCursor(self.selected + 1)
  end

  if key == "A" then
    self.listWidget[self.selected]:action()
  end

  if key == "B" then
    self:cancelAction()
  end

end

function TextMenu:mousemoved(x, y)
  self.selected = self.begin + math.floor(y / self.widgetsH)
  if self.selected < 1 then
    self.selected = 1
  end
  if self.selected > #self.listWidget then
    self.selected = #self.listWidget
  end
end

function TextMenu:mousepressed(x, y, button, isTouch)
  self.selected = self.begin + math.floor(y / self.widgetsH)
  if self.selected < 1 then
    self.selected = 1
  end
  if self.selected > #self.listWidget then
    self.selected = #self.listWidget
  end
  if #self.listWidget > 0 then
    self.listWidget[self.selected]:action()
  end
end

function TextMenu:draw()
  local widgety = self.y
  self.font:set()
  for i,v in ipairs(self.listWidget) do
    if (i >= self.begin) and (i < self.begin + self.slots) then
      if self.selected == i and self.focus == true then
        love.graphics.setColor(85, 170, 255)
      else
        utils.graphics.resetColor()
      end
      if (self.center) then
        love.graphics.printf(v.label, self.x, widgety, self.w, "center")
      else
        love.graphics.print(v.label, self.x, widgety)
      end
      widgety = widgety + self.widgetsH
    end
  end
end
