/*
 * Copyright 2016 - 2024 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#include <studio/undostack.hpp>

namespace studio {

bool UndoCommand::mergeWith(UndoCommand const*) noexcept {
	return false;
}

void UndoStack::push(ox::UPtr<UndoCommand> &&cmd) noexcept {
	for (auto const i = m_stackIdx; i < m_stack.size();) {
		oxIgnoreError(m_stack.erase(i));
	}
	cmd->redo();
	redoTriggered.emit(cmd.get());
	changeTriggered.emit(cmd.get());
	if (m_stack.empty() || !(*m_stack.back().value)->mergeWith(cmd.get())) {
		m_stack.emplace_back(std::move(cmd));
		++m_stackIdx;
	}
}

void UndoStack::redo() noexcept {
	if (m_stackIdx < m_stack.size()) {
		auto &c = m_stack[m_stackIdx++];
		c->redo();
		redoTriggered.emit(c.get());
		changeTriggered.emit(c.get());
	}
}

void UndoStack::undo() noexcept {
	if (m_stackIdx) {
		auto &c = m_stack[--m_stackIdx];
		c->undo();
		undoTriggered.emit(c.get());
		changeTriggered.emit(c.get());
	}
}

}
