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

#include "undostack.hpp"

namespace nostalgia::studio {

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

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

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());
	}
}

}
