local task = require "lib.utils.task"

--- Отвечает за перемещение по тайлам
--- @class TiledBehavior : Behavior
--- @field size Vec3
local behavior = {}
behavior.__index = behavior
behavior.id = "tiled"

--- @param size? Vec3
function behavior.new(size)
    return setmetatable({
        size = size or Vec3({ 1, 1 }),
    }, behavior)
end

--- @param path Deque
--- @return Task<nil>
function behavior:followPath(path)
    if path:is_empty() then return task.fromValue(nil) end

    self.owner:try(Tree.behaviors.sprite, function(sprite)
        sprite:loop("run")
    end)

    -- Рекурсивная функция для прохода по пути
    local function nextStep()
        if path:is_empty() then
            self.owner:try(Tree.behaviors.sprite, function(sprite)
                sprite:loop("idle")
            end)
            return task.fromValue(nil)
        end

        local nextCell = path:pop_front()
        return task.chain(self:runTo(nextCell), nextStep)
    end

    return nextStep()
end

--- @param target Vec3
--- @return Task<nil>
function behavior:runTo(target)
    local positioned = self.owner:has(Tree.behaviors.positioned)
    if not positioned then return task.fromValue(nil) end

    self.owner:try(Tree.behaviors.sprite,
        function(sprite)
            if target.x < positioned.position.x then
                sprite.side = Tree.behaviors.sprite.LEFT
            elseif target.x > positioned.position.x then
                sprite.side = Tree.behaviors.sprite.RIGHT
            end
        end
    )

    local distance = target:subtract(positioned.position):length()
    local duration = distance * 500 -- 500ms per unit

    return task.tween(positioned, { position = target }, duration)
end

function behavior:update(dt)
    -- Logic moved to tasks
end

return behavior
