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

#include "commands.hpp"
#include "updatecolorcommand.hpp"

namespace nostalgia::gfx {

UpdateColorCommand::UpdateColorCommand(
	Palette &pal,
	size_t const page,
	size_t const idx,
	Color16 const newColor):
		m_pal{pal},
		m_page{page},
		m_idx{idx},
		m_altColor{newColor} {
	if (color(m_pal, m_page, m_idx) == newColor) {
		throw studio::NoChangesException();
	}
}

bool UpdateColorCommand::mergeWith(UndoCommand &cmd) noexcept {
	if (cmd.commandId() != static_cast<int>(PaletteEditorCommandId::UpdateColor)) {
		return false;
	}
	auto ucCmd = dynamic_cast<UpdateColorCommand const*>(&cmd);
	if (m_idx != ucCmd->m_idx) {
		return false;
	}
	return true;
}

int UpdateColorCommand::commandId() const noexcept {
	return static_cast<int>(PaletteEditorCommandId::UpdateColor);
}

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

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

void UpdateColorCommand::swap() noexcept {
	auto &dst = colors(m_pal, m_page)[m_idx];
	std::swap(dst, m_altColor);
}

}