#include "pch.h"

#include "legacy_history_services.h"

#include "action.h"

#include <limits>

namespace pp::panopainter {
namespace {

[[nodiscard]] int saturated_history_metric(size_t value) noexcept
{
    constexpr auto max_int = static_cast<size_t>(std::numeric_limits<int>::max());
    return value > max_int ? std::numeric_limits<int>::max() : static_cast<int>(value);
}

class LegacyHistoryUiServices final : public pp::app::HistoryUiServices {
public:
    void invoke_undo() override
    {
        ActionManager::undo();
    }

    void invoke_redo() override
    {
        ActionManager::redo();
    }

    void clear_history() override
    {
        ActionManager::clear();
    }
};

} // namespace

LegacyHistorySnapshot legacy_history_snapshot() noexcept
{
    return LegacyHistorySnapshot {
        .undo_count = saturated_history_metric(ActionManager::I.m_actions.size()),
        .redo_count = saturated_history_metric(ActionManager::I.m_redos.size()),
        .memory_bytes = saturated_history_metric(ActionManager::I.m_memory),
    };
}

pp::foundation::Status execute_legacy_history_plan(const pp::app::HistoryUiPlan& plan)
{
    LegacyHistoryUiServices services;
    return pp::app::execute_history_ui_plan(plan, services);
}

void clear_legacy_history() noexcept
{
    ActionManager::clear();
}

} // namespace pp::panopainter
