--- @class SpellcasterBehavior : Behavior
--- @field spellbook Spell[] собственный набор спеллов персонажа
--- @field cast Spell | nil ссылка на активный спелл из спеллбука
--- @field cooldowns {[string]: integer} текущий кулдаун спеллов по тегам
--- @field state "idle" | "casting" | "running"
local behavior = {}
behavior.__index = behavior
behavior.id = "spellcaster"
behavior.state = "idle"
behavior.cooldowns = {}

---@param spellbook Spell[] | nil
---@return SpellcasterBehavior
function behavior.new(spellbook)
    local spb = require "lib.spellbook" --- @todo временное добавление ходьбы (и читов) всем персонажам
    local t = {}
    t.spellbook = spellbook or spb.of { spb.walk, spb.regenerateMana, spb.attack }
    t.cooldowns = {}
    return setmetatable(t, behavior)
end

function behavior:endCast()
    self.owner:try(Tree.behaviors.effects, function(effects)
        effects:afterCast()
    end)
    self.state = "idle"
    self.cast = nil
    Tree.level.turnOrder:reorder()
    Tree.level.selector:unlock()
end

function behavior:processCooldowns()
    local cds = {}
    for tag, cd in pairs(self.cooldowns) do
        cds[tag] = (cd - 1) >= 0 and cd - 1 or 0
    end
    self.cooldowns = cds
end

function behavior:update(dt)
    if Tree.level.selector:deselected() then
        self.state = "idle"
        self.cast = nil
    end
    if self.cast and self.state == "casting" then self.cast:update(self.owner, dt) end
end

function behavior:draw()
    if self.cast and self.state == "casting" then self.cast:draw() end
end

return behavior
