local cwd  = (...):gsub('%.listbox$', '') .. "."
local Menu = require(cwd .. "parent")

ListBox = Menu:extend()

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

function ListBox:updateWidgetSize()
  self.widget.h = math.floor( self.h / self.slots )
  self.widget.w = self.w
end

function ListBox:update(dt)
  if self.widget.selected < self.begin then
    self.begin = self.widget.selected
  end
  if self.widget.selected > self.begin + self.slots - 1 then
    self.begin = self.widget.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.widget.selected - 1)
  end

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

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

end

function ListBox:mousemoved(x, y)
  self.widget.selected = self.begin + math.floor(y / self.widget.h)
  if self.widget.selected < 1 then
    self.widget.selected = 1
  end
  if self.widget.selected > #self.widget.list then
    self.widget.selected = #self.widget.list
  end
end

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

function ListBox:draw()
  local widgety = self.y
  for i,v in ipairs(self.widget.list) do
    if (i >= self.begin) and (i < self.begin + self.slots) then
      v:draw(self.x, widgety, self.w, self.widget.h)
      if self.widget.selected == i and self.focus == true then
        v:drawSelected(self.x, widgety, self.w, self.widget.h)
      else
        v:draw(self.x, widgety, self.w, self.widget.h)
      end
      widgety = widgety + self.widget.h
    end
  end
end

return ListBox
