MenuController = Object:extend()

require "modules.menus.menu"
require "modules.menus.widgets"
require "modules.menus.listbox"
require "modules.menus.flowbox"
require "modules.menus.grid"
require "modules.menus.textmenu"


function MenuController:new()
  self.menus = {}
end

function MenuController:reset()
  self.menus = {}
end

function MenuController:addMenu(menu)
  table.insert(self.menus, menu)
end

function MenuController:update()
  self:clear()
  for i,v in ipairs(self.menus) do
    v.id = i
    v:update(dt)
    v:updateWidgets(dt)
  end
end

function MenuController:clear()
 -- On retire les entitées marquées comme supprimées
  for i,v in ipairs(self.menus) do
    if (v.destroyed == true) then
      table.remove(self.menus, i)
    end
  end
end

function MenuController:updateList()
  for i,v in ipairs(self.menus) do
    v.id = i
  end
end

function MenuController:keyreleased(key, code)
  for i,v in ipairs(self.menus) do
    if v.focus == true then
      v:keyreleased(key, code)
    end
  end
end

function MenuController:mousemoved(x, y, dx, dy)
  for i,v in ipairs(self.menus) do
    if (x > v.x) and (x < v.x + v.w) and (y > v.y) and (y < v.y + v.h) then
      v:mousemoved(x - v.x, y - v.y)
      for j,u in ipairs(self.menus) do
        u.focus = false
      end
      v.focus = true
    end
  end
end

function MenuController:mousepressed( x, y, button, istouch )
  for i,v in ipairs(self.menus) do
    if (x > v.x) and (x < v.x + v.w) and (y > v.y) and (y < v.y + v.h) then
      v:mousepressed(x - v.x, y - v.y, button, istouch )
      for j,u in ipairs(self.menus) do
        u.focus = false
      end
      v.focus = true
    end
  end
end

function MenuController:draw(dt) -- On dessine les entitées
  for i,v in ipairs(self.menus) do
    v.id = i
    v:draw(dt)
  end
end

return MenuController
