local ParentScreen = require "scenes.overworld.screens.parent"
local CharacterScreen = ParentScreen:extend()

local menu = require "game.modules.menus.fancy"
local gui = require "game.modules.gui"
local const = require "scenes.overworld.screens.mainmenu.const"

local BasicPage = require "scenes.overworld.screens.mainmenu.character.basicpage"
local pageList = {BasicPage}

local ReturnWidget = menu.BaseWidget:extend()

function CharacterScreen:new(scene, character)
  self.character = game.characters.list[character]
  self.charName = character

  self.page = BasicPage(self, character)
  self.pageIndex = 1

  self.artwork = love.graphics.newImage("datas/gamedata/characters/" .. character .. "/artwork.png")
  self.artworkOrigin = require("datas.gamedata.characters." .. character .. ".artwork")
  CharacterScreen.super.new(self, scene, self.character.name)
end

function CharacterScreen:update(dt)
  local keys = self.scene:getKeys(1)
  if (keys["left"].isPressed) then
    self:setPage(self.pageIndex - 1)
  end
  if (keys["right"].isPressed) then
    self:setPage(self.pageIndex + 1)
  end
end

function CharacterScreen:setPage(newPageIndex)
  local newPageIndex = newPageIndex or 1
  if (newPageIndex > #pageList) then
    newPageIndex = 1
  end
  if (newPageIndex < 1) then
    newPageIndex = #pageList
  end

  self.pageIndex = newPageIndex
  self.page = pageList[self.pageIndex](self, self.charName)
  self.scene.menusystem:reset()
  self:setMenu()
end

function CharacterScreen:setMenu()
  local itemNumber = 1
  local y = const.Y2 - (16*itemNumber) + 2
  menu.FancyMenu(self.scene, "menu", const.X2 - 128 - 14, y, 128, 1, false)
  self.page:getMenuWidgets()
  --menu.BaseWidget(self.scene, "equip", "Change talent", ">")
  --menu.BaseWidget(self.scene, "equip", "Battle skills", ">")
  --menu.BaseWidget(self.scene, "equip", "Equipement", ">")
  ReturnWidget(self.scene, self.charName)

  self.scene.menusystem:switchMenu("menu")
  self.scene.menusystem.menus["menu"]:getFocus()
  self.scene.menusystem.menus["menu"]:setCancelWidget()
end

function CharacterScreen:draw()
  self.scene.assets.fonts["small"]:setLineHeight(16/18)
  if (self.page ~= nil) then
    self.page:draw()
  end
end

function CharacterScreen:drawBackground()
  love.graphics.draw(self.artwork, self.artworkOrigin.x, self.artworkOrigin.y)
end

-- Widgets

function ReturnWidget:new(scene, charName)
  self.charName = charName
  ReturnWidget.super.new(self, scene, "menu", "Back", "")
end

function ReturnWidget:action()
  for i, name in ipairs(game.characters.team) do
    if (name == self.charName) then
      self.widgetSelected = i
    end
  end

  self.scene.screens.mainmenu["pause"](self.scene, "character", self.widgetSelected)
end

return CharacterScreen
