local ListBox = require "core.modules.menusystem.listbox"
local Widget  = require "core.modules.menusystem.widgets"

local MenuConstructor = Object:extend()
local CharacterMenu   = require "scenes.battlesystem.menus.battlemenu"
local widgets         = require "scenes.battlesystem.menus.widgets"

function MenuConstructor:new( controller )
  self.scene = controller
end

function MenuConstructor:reconstruct(character)
  core.debug:print("cbs/menu", "Reconstructing the menu")
  self.scene.menusystem:reset()
  self:build(character)

  self.scene.menusystem:switchMenu("BaseMenu")
end

function MenuConstructor:build(character)
  core.debug:print("cbs/menu", "Building the menu")
  self:buildBaseMenu(character)
  self:buildSkillMenu(character)
  self:buildObjectMenu(character)

  self.scene.menusystem.menus["BaseMenu"]:finalize()
  self.scene.menusystem:setSoundFromSceneAssets("mBeep")
  self.scene.menusystem:activate()
end

function MenuConstructor:buildBaseMenu(character)
  CharacterMenu(self.scene, "BaseMenu")
  widgets.ActionWidget(character, "BaseMenu", "attack", "Attack")
  self:addSubMenu("BaseMenu", "SkillMenu", "Skills")
  self:addSubMenu("BaseMenu", "ObjectMenu", "Objects")
  widgets.ActionWidget(character, "BaseMenu", "defend", "Defend")
  widgets.ActionWidget(character, "BaseMenu", "flee", "Flee")
end

function MenuConstructor:set(currentCharacter)
  self:reconstruct(currentCharacter)
end

function MenuConstructor:buildSkillMenu(character)
  local list = character.abstract.skills
  for k, skill in pairs(list) do
    widgets.SkillWidget(character, "SkillMenu", skill.name, "")
  end
  --SubMenuWidget(character,  "SkillMenu", "back", "BaseMenu")

  self.scene.menusystem.menus["SkillMenu"]:setCancelWidget()
end

function MenuConstructor:buildObjectMenu(character)
  for i,pocket in ipairs(game.loot.inventory) do
    if (pocket.inBattle) then
      CharacterMenu(self.scene, pocket.name)
      self:addSubMenu("ObjectMenu", pocket.name, pocket.fullname)
      for j,itemData in ipairs(pocket.list) do
        widgets.ItemWidget(character, pocket.name, itemData.name)
      end
    end
  end
  self.scene.menusystem.menus["ObjectMenu"]:setCancelWidget()
end

function MenuConstructor:addSubMenu(menu, submenu, widgetName)
  self.scene.menusystem.menus[menu]:addSubMenu(submenu, widgetName)
end

function MenuConstructor:unset(  )
  self.isActive = false
end

return MenuConstructor
