ListBox = Menu:extend()

function ListBox:new(x,y,w,h,slots)
  ListBox.super.new(self, x, y, w, h)
  self.slots = slots
  self.begin = 1
  self.widgetsH = math.floor( self.h / slots )
  self.h = slots * self.widgetsH -- On fait en sorte que la hauteur
  -- soit un multiple du nombre de slot et de leur hauteur
end

function ListBox:update(dt)
  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 ListBox:keyreleased(key, code)
  
  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

end

function ListBox: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 ListBox: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 ListBox:draw()
  local widgety = self.y
  for i,v in ipairs(self.listWidget) do
    if (i >= self.begin) and (i < self.begin + self.slots) then
      v:draw(self.x, widgety, self.w, self.widgetsH)
      if self.selected == i and self.focus == true then
        v:drawSelected(self.x, widgety, self.w, self.widgetsH)
      else
        v:draw(self.x, widgety, self.w, self.widgetsH)
      end
      widgety = widgety + self.widgetsH
    end
  end
end
