#include "pch.h"
#include "log.h"
#include "action.h"
#include "app.h"

ActionManager ActionManager::I;

void ActionManager::add(Action *action)
{
    I.m_redos = std::stack<std::unique_ptr<Action>>();
    I.m_actions.emplace(action);
    I.m_memory += action->memory();
    //LOG("History: %.2f KB", I.m_memory / 1024.f);
    App::I->update_memory_usage(I.m_memory);
}

void ActionManager::undo()
{
    if (I.m_actions.empty())
        return;

    if (auto action = I.m_actions.top()->get_redo())
    {
        I.m_redos.emplace(action);
        I.m_redos.top()->was_saved = !Canvas::I->m_unsaved;
    }

    if (auto action = std::move(I.m_actions.top()))
    {
        I.m_actions.pop();
        action->undo();
        I.m_memory -= action->memory();
        Canvas::I->m_unsaved = !action->was_saved;
    }
    //LOG("History: %.2f KB", I.m_memory / 1024.f);
    App::I->update_memory_usage(I.m_memory);
    App::I->title_update();
}

void ActionManager::redo()
{
    if (I.m_redos.empty())
        return;

    if (auto action = I.m_redos.top()->get_redo())
    {
        I.m_actions.emplace(action);
        I.m_actions.top()->was_saved = !Canvas::I->m_unsaved;
        I.m_memory += I.m_actions.top()->memory();
    }

    if (auto action = std::move(I.m_redos.top()))
    {
        I.m_redos.pop();
        action->undo();
        Canvas::I->m_unsaved = !action->was_saved;
    }
    //LOG("History: %.2f KB", I.m_memory / 1024.f);
    App::I->update_memory_usage(I.m_memory);
    App::I->title_update();
}

void ActionManager::clear()
{
    while (!I.m_actions.empty())
        I.m_actions.pop();
    while (!I.m_redos.empty())
        I.m_redos.pop();
    I.m_memory = 0;
    //LOG("History: %.2f KB", I.m_memory / 1024.f);
    App::I->update_memory_usage(I.m_memory);
}
