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

#include "commands.hpp"
#include "updatecolorinfocommand.hpp"

namespace nostalgia::gfx {

UpdateColorInfoCommand::UpdateColorInfoCommand(
		Palette &pal,
		size_t idx,
		ox::StringParam newColorInfo):
		m_pal(pal),
		m_idx(idx),
		m_altColorInfo(std::move(newColorInfo)) {
	if (m_pal.colorNames[m_idx] == m_altColorInfo) {
		throw studio::NoChangesException();
	}
}

bool UpdateColorInfoCommand::mergeWith(UndoCommand &cmd) noexcept {
	if (cmd.commandId() != static_cast<int>(PaletteEditorCommandId::UpdateColorInfo)) {
		return false;
	}
	auto ucCmd = dynamic_cast<UpdateColorInfoCommand const*>(&cmd);
	if (m_idx != ucCmd->m_idx) {
		return false;
	}
	m_pal.colorNames[m_idx] = std::move(ucCmd->m_pal.colorNames[m_idx]);
	setObsolete(m_altColorInfo == m_pal.colorNames[m_idx]);
	return true;
}

int UpdateColorInfoCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::UpdateColorInfo);
}

ox::Error UpdateColorInfoCommand::redo() noexcept {
	swap();
	return {};
}

ox::Error UpdateColorInfoCommand::undo() noexcept {
	swap();
	return {};
}

void UpdateColorInfoCommand::swap() noexcept {
	std::swap(m_pal.colorNames[m_idx], m_altColorInfo);
}

}