local Element = require "lib.simple_ui.element"
local Rect = require "lib.simple_ui.rect"
local Color = require "lib.simple_ui.color"
local Bar = require "lib.simple_ui.level.bar"

--- @class BottomBars : UIElement
--- @field hpBar BarElement
--- @field manaBar BarElement
local bottomBars = setmetatable({}, Element)
bottomBars.__index = bottomBars;

--- @param cid Id
function bottomBars.new(cid)
    local t = setmetatable({}, bottomBars)

    t.hpBar =
        Bar {
            getter = function()
                local char = Tree.level.characters[cid]
                return char:try(Tree.behaviors.stats, function(stats)
                    return stats.hp or 0
                end)
            end,
            color = Color { r = 130 / 255, g = 8 / 255, b = 8 / 255 },
            drawText = true,
            maxValue = 20
        }

    t.manaBar =
        Bar {
            getter = function()
                local char = Tree.level.characters[cid]
                return char:try(Tree.behaviors.stats, function(stats)
                    return stats.mana or 0
                end)
            end,
            color = Color { r = 51 / 255, g = 105 / 255, b = 30 / 255 },
            useDividers = true,
            maxValue = 10
        }


    return t
end

function bottomBars:update(dt)
    local height = 16
    local margin = 2

    self.bounds.height = height
    self.bounds.y = self.bounds.y - height

    self.hpBar.bounds = Rect {
        width = -2 * margin + self.bounds.width / 2,
        height = height - margin,
        x = self.bounds.x + margin,
        y = self.bounds.y + margin
    }

    self.manaBar.bounds = Rect {
        width = -2 * margin + self.bounds.width / 2,
        height = height - margin,
        x = self.bounds.x + margin + self.bounds.width / 2,
        y = self.bounds.y + margin
    }

    self.hpBar:update(dt)
    self.manaBar:update(dt)
end

function bottomBars:draw()
    -- шум
    love.graphics.setShader(Tree.assets.files.shaders.soft_uniform_noise)
    love.graphics.rectangle("fill", self.bounds.x, self.bounds.y, self.bounds.width, self.bounds.height)
    love.graphics.setShader()

    love.graphics.setColor(38 / 255, 50 / 255, 56 / 255)
    love.graphics.setBlendMode("multiply", "premultiplied")
    love.graphics.rectangle("fill", self.bounds.x, self.bounds.y, self.bounds.width, self.bounds.height)
    love.graphics.setBlendMode("alpha")

    self.hpBar:draw()
    self.manaBar:draw()
end

return bottomBars.new
