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

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

local baseCharacterMenu = require "scenes.overworld.screens.mainmenu.common.charmenu"
local baseCharacterWidget = require "scenes.overworld.screens.mainmenu.common.charwidget"
local CharacterMenu = baseCharacterMenu:extend()
local CharacterWidget = baseCharacterWidget:extend()

local EffectManager = require "game.loot.effectManager"

local DESC_SIZE = 32 * 4

function UseItemsScreen:new(scene, category, item, widgetId)
    UseItemsScreen.super.new(self, scene, "Use item")
    self.category = category
    self.item = item
    self.itemData = game.loot:getItemData(category, self.item.name)
    self.widgetId = widgetId

    self.choiceBack = gui.newChoiceBack(48 + 16)
    self.descBox = gui.newTextBox("assets/gui/dialogbox.png", DESC_SIZE, 40 + 48)

    self.desc = self.itemData.description
    self.effects = game.loot:getEffectStrings(self.category, self.item.name)

    self.effectManager = EffectManager()
    self.effectManager:getItemData(category, self.item.name)
end

function UseItemsScreen:setMenu()
    CharacterMenu(self.scene)
    for i, name in ipairs(game.characters.team) do
        CharacterWidget(self.scene, name)
    end
    self.scene.menusystem:switchMenu("character")
end

function UseItemsScreen:draw()
    self.scene.assets.fonts["small"]:setLineHeight(16 / 18)
    self:drawPocket()
    self:drawDescription(const.X, const.Y)
end

function UseItemsScreen:drawDescription(x, y)
    love.graphics.draw(self.descBox, x, y)
    local xx, yy, ww = x + 6, y + 4, DESC_SIZE - 12
    self.scene.assets.fonts["small"]:draw(self.itemData.fullname .. ":\n" .. self.effects, xx, yy, ww, "left")
end

function UseItemsScreen:drawPocket()
    local x = const.X + DESC_SIZE - 48
    local y = const.Y2 - 24
    love.graphics.draw(self.choiceBack, x, y)

    self.scene.assets.fonts["small"]:draw("x" .. self.item.number, x + 16, y - 2, -1, "left")
end

function UseItemsScreen:goBack()
    self.scene.screens.mainmenu["items"](self.scene, game.loot:getPocketIdByName(self.category), self.widgetId)
end

function UseItemsScreen:useItem(charName)
    local character = game.characters.list[charName]
    self.effectManager:applyEffects(character)
    if (self.item.number <= 1) then
        game.loot:removeItem(self.category, self.item.name, 1)
        self:goBack()
    else
        game.loot:removeItem(self.category, self.item.name, 1)
    end
end

-- Character menu
function CharacterMenu:cancelAction()
    -- Switch à l'écran précédant
    self.scene.currentScreen:goBack()
end

-- Hero custom widget
--
function CharacterWidget:action()
    self.scene.currentScreen:useItem(self.charName)
end

return UseItemsScreen
